HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcppCritical

How do you loop through a std::map?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
youhowstdloopthroughmap

Problem

I want to iterate through each element in the map without knowing any of its string-int values or keys.

What I have so far:

void output(map table)
{
       map::iterator it;
       for (it = table.begin(); it != table.end(); it++)
       {
            //How do I access each element?  
       }
}

Solution

You can achieve this like following :

map::iterator it;

for (it = table.begin(); it != table.end(); it++)
{
    std::cout first    // string (key)
              second   // string's value 
              << std::endl;
}


With C++11 ( and onwards ),

for (auto const& x : table)
{
    std::cout << x.first  // string (key)
              << ':' 
              << x.second // string's value 
              << std::endl;
}


With C++17 ( and onwards ),

for (auto const& [key, val] : table)
{
    std::cout << key        // string (key)
              << ':'  
              << val        // string's value
              << std::endl;
}

Code Snippets

map<string, int>::iterator it;

for (it = table.begin(); it != table.end(); it++)
{
    std::cout << it->first    // string (key)
              << ':'
              << it->second   // string's value 
              << std::endl;
}
for (auto const& x : table)
{
    std::cout << x.first  // string (key)
              << ':' 
              << x.second // string's value 
              << std::endl;
}
for (auto const& [key, val] : table)
{
    std::cout << key        // string (key)
              << ':'  
              << val        // string's value
              << std::endl;
}

Context

Stack Overflow Q#26281979, score: 1031

Revisions (0)

No revisions yet.