c++dictionaryfor-loopprintingstd-pair

How can I print out C++ map values?


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?


Solution

  • 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(const auto& elem : myMap)
    {
       std::cout << elem.first << " " << elem.second.first << " " << elem.second.second << "\n";
    }