Search code examples
c++vectormultimap

Print multimap<string, vector<string>>?


I am trying to display the contents of a multimap with a string and a vector as key and value, respectively. I run into problems when I try to dislpay the contents of the vector (value in multimap). What I have done so far is:

    multimap<string, vector<string> > someMultimap;
    vector<string> someVector;
    someVector.push_back("test");
    someMultimap.insert(pair<string, vector<string> >("KEY", someVector));
    //So for it works fine...

    multimap <string, vector<string> >::iterator it;

    for (it = someMultimap.begin(); it != someMultimap.end(); ++it)
    {
        cout << it->first << endl << endl << it->second << endl << endl;
                                             ^^^^^^^^^^
                                          this is the problem, can´t do this with a vector(?)
    }

Does anyone have a suggestion for solving the problem?


Solution

  • You can add a second loop for the vector.

    multimap <string, vector<string> >::const_iterator it;
    
    for (it = someMultimap.begin(); it != someMultimap.end(); ++it)
    {
        cout << it->first << endl ;
    
        vector<string>::const_iterator itVec;
        for (itVec = it->second.begin(); itVec != it->second.end(); ++itVec)
        {
            cout << *itVec <<" ";
        }
        cout<<endl;
    }
    

    If you don't plan to modify any value you can make your iterators const