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

前端 未结 7 1519
轻奢々
轻奢々 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 :

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

    Test program:

    #include 
    #include 
    #include 
    #include 
    #include 
    using namespace std;
    
    void printPair(const pair > &p)
    {
        cout << "Key: " << p.first << endl;
        copy(p.second.begin(), p.second.end(), ostream_iterator(cout, "\n"));
    }
    
    int main()
    {
        map >  mapex;
    
        list mylist1;
        mylist1.push_back("item 1");
        mylist1.push_back("item 2");
        mapex["foo"] =  mylist1;
        list 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);
    }
    

提交回复
热议问题