我可以用cout而不是迭代器循环打印STL映射

时间:2013-09-04 02:19:21

标签: c++ map

#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;而不是使用iterator。因为我确实看到一些代码可以直接使用简单的cout << Anythg打印地图内容。我想知道是什么让代码工作了吗?

1 个答案:

答案 0 :(得分:3)

Nop,或者至少标准库没有为容器和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);
}