2
#include <string>
#include <iostream>
#include <map>
#include <utility>
using namespace std;


int main()
{

   map<int, string> Employees;

   // 1) Assignment using array index notation
   Employees[5234] = "Mike C.";
   Employees[3374] = "Charlie M.";
   Employees[1923] = "David D.";
   Employees[7582] = "John A.";
   Employees[5328] = "Peter Q.";

   cout << Employees;

   cout << "Employees[3374]=" << Employees[3374] << endl << endl;

   cout << "Map size: " << Employees.size() << endl;

   /*for( map<int,string>::iterator ii=Employees.begin(); ii!=Employees.end(); ++ii)
   {
       cout << (*ii).first << ": " << (*ii).second << endl;
   }*/
   system("pause");
}

我想知道要添加什么才能打印cout << Employees;而不是使用迭代器。因为我确实看到一些代码可以直接用简单的 . 打印地图内容cout << Anythg。我想知道是什么让代码工作?

4

1 回答 1

3

不,或者至少标准库不提供operator <<容器和std::ostream.

查看https://github.com/louisdx/cxx-prettyprint或编写自己的operator<<(std::ostream &, const std::map<T1, T2> &).

以下是简单的实现,例如:

#include <map>
#include <string>
#include <iostream>

template<typename T1, typename T2>
std::ostream &operator<<(std::ostream &stream, const std::map<T1, T2>& map)
{
  for (typename std::map<T1, T2>::const_iterator it = map.begin();
       it != map.end();
       ++it)
    {
      stream << (*it).first << " --> " << (*it).second << std::endl;
    }
  return stream;
}

int     main(int, char **)
{
  std::map<std::string, int> bla;

  bla["one"] =  1;
  bla["two"] = 2;
  std::cout << bla << std::endl;
  return (0);
}
于 2013-09-04T02:22:18.833 回答