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


Question

I have a map declared as follows:

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

How can I display the items stored in the above map on the console?

1
31
3/21/2019 9:27:06 AM

Accepted Answer

Well it depends on how you want to display them, but you can always iterate them easily:

typedef map<string, list<string>>::const_iterator MapIterator;
for (MapIterator iter = mapex.begin(); iter != mapex.end(); iter++)
{
    cout << "Key: " << iter->first << endl << "Values:" << endl;
    typedef list<string>::const_iterator ListIterator;
    for (ListIterator list_iter = iter->second.begin(); list_iter != iter->second.end(); list_iter++)
        cout << " " << *list_iter << endl;
}
24
6/30/2009 1:04:06 PM

Update (Back to the future): with C++11 range-based for loops –

std::map<Key, Value> m { ... /* initialize it */ ... };

for (const auto &p : m) {
    std::cout << "m[" << p.first << "] = " << p.second << '\n';
}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon