How can I print out C++ map values?

laxxers picture laxxers · Dec 28, 2012 · Viewed 206.1k times · Source

I have a map like this:

map<string, pair<string,string> > myMap;

And I've inserted some data into my map using:

myMap.insert(make_pair(first_name, make_pair(middle_name, last_name)));

How can I now print out all the data in my map?

Answer

Armen Tsirunyan picture Armen Tsirunyan · Dec 28, 2012
for(map<string, pair<string,string> >::const_iterator it = myMap.begin();
    it != myMap.end(); ++it)
{
    std::cout << it->first << " " << it->second.first << " " << it->second.second << "\n";
}

In C++11, you don't need to spell out map<string, pair<string,string> >::const_iterator. You can use auto

for(auto it = myMap.cbegin(); it != myMap.cend(); ++it)
{
    std::cout << it->first << " " << it->second.first << " " << it->second.second << "\n";
}

Note the use of cbegin() and cend() functions.

Easier still, you can use the range-based for loop:

for(auto elem : myMap)
{
   std::cout << elem.first << " " << elem.second.first << " " << elem.second.second << "\n";
}