c++ - Can I print STL map with cout instead of iterator loop -


#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"); } 

i know add in order me print cout << employees; instead of using iterator.because did see code can directly print map content simple cout << anythg.i wonder has made code work?

nop, or @ least standard library doesn't provide default implementation of operator << container , std::ostream.

check out https://github.com/louisdx/cxx-prettyprint or write own implementation of operator<<(std::ostream &, const std::map<t1, t2> &).

here simple implemenation, sake of example:

#include <map> #include <string> #include <iostream>  template<typename t1, typename t2> std::ostream &operator<<(std::ostream &stream, const std::map<t1, t2>& map) {   (typename std::map<t1, t2>::const_iterator = map.begin();        != 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); } 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -