How can I display the content of a map on the console?

前端 未结 7 1456
轻奢々
轻奢々 2020-12-28 13:41

I have a map declared as follows:

map < string , list < string > > mapex ; list< string > li;

How can I disp

相关标签:
7条回答
  • 2020-12-28 14:08

    Another form, using <algorithm>:

    void printPair(const pair<string, list<string> > &p)
    {
        cout << "Key: " << p.first << endl;
        copy(p.second.begin(), p.second.end(), ostream_iterator<string>(cout, "\n"));
    }    
    for_each(mapex.begin(), mapex.end(), printPair);
    

    Test program:

    #include <iostream>
    #include <map>
    #include <list>
    #include <iterator>
    #include <algorithm>
    using namespace std;
    
    void printPair(const pair<string, list<string> > &p)
    {
        cout << "Key: " << p.first << endl;
        copy(p.second.begin(), p.second.end(), ostream_iterator<string>(cout, "\n"));
    }
    
    int main()
    {
        map<string, list<string> >  mapex;
    
        list<string> mylist1;
        mylist1.push_back("item 1");
        mylist1.push_back("item 2");
        mapex["foo"] =  mylist1;
        list<string> mylist2;
        mylist2.push_back("item 3");
        mylist2.push_back("item 4");
        mylist2.push_back("item 5");
        mapex["bar"] =  mylist2;
    
        for_each(mapex.begin(), mapex.end(), printPair);
    }
    
    0 讨论(0)
提交回复
热议问题