dictionary – How can I print out C++ map values?

dictionary – How can I print out C++ map values?

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 dont 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;
}

If your compiler supports (at least part of) C++11 you could do something like:

for (auto& t : myMap)
    std::cout << t.first <<   
              << t.second.first <<   
              << t.second.second << n;

For C++03 Id use std::copy with an insertion operator instead:

typedef std::pair<string, std::pair<string, string> > T;

std::ostream &operator<<(std::ostream &os, T const &t) { 
    return os << t.first <<   << t.second.first <<   << t.second.second;
}

// ...
std:copy(myMap.begin(), myMap.end(), std::ostream_iterator<T>(std::cout, n));

dictionary – How can I print out C++ map values?

Since C++17 you can use range-based for loops together with structured bindings for iterating over your map. This improves readability, as you reduce the amount of needed first and second members in your code:

std::map<std::string, std::pair<std::string, std::string>> myMap;
myMap[x] = { a, b };
myMap[y] = { c, d };

for (const auto &[k, v] : myMap)
    std::cout << m[ << k << ] = ( << v.first << ,  << v.second << )  << std::endl;

Output:

m[x] = (a, b)
m[y] = (c, d)

Code on Coliru

Leave a Reply

Your email address will not be published.