C++ Loop through Map

C++Dictionary

C++ Problem Overview


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

What I have so far:

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

C++ Solutions


Solution 1 - C++

You can achieve this like following :

map<string, int>::iterator it;

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

With C++11 ( and onwards ),

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

With C++17 ( and onwards ),

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

Solution 2 - C++

Try the following

for ( const auto &p : table )
{
   std::cout << p.first << '\t' << p.second << std::endl;
} 

The same can be written using an ordinary for loop

for ( auto it = table.begin(); it != table.end(); ++it  )
{
   std::cout << it->first << '\t' << it->second << std::endl;
} 

Take into account that value_type for std::map is defined the following way

typedef pair<const Key, T> value_type

Thus in my example p is a const reference to the value_type where Key is std::string and T is int

Also it would be better if the function would be declared as

void output( const map<string, int> &table );

Solution 3 - C++

The value_type of a map is a pair containing the key and value as it's first and second member, respectively.

map<string, int>::iterator it;
for (it = symbolTable.begin(); it != symbolTable.end(); it++)
{
    std::cout << it->first << ' ' << it->second << '\n';
}

Or with C++11, using range-based for:

for (auto const& p : symbolTable)
{
    std::cout << p.first << ' ' << p.second << '\n';
}

Solution 4 - C++

As @Vlad from Moscow says, Take into account that value_type for std::map is defined the following way:

typedef pair<const Key, T> value_type

This then means that if you wish to replace the keyword auto with a more explicit type specifier, then you could this;

for ( const pair<const string, int> &p : table ) {
   std::cout << p.first << '\t' << p.second << std::endl;
} 

Just for understanding what auto will translate to in this case.

Solution 5 - C++

As P0W has provided complete syntax for each C++ version, I would like to add couple of more points by looking at your code

  • Always take const & as argument as to avoid extra copies of the same object.
  • use unordered_map as its always faster to use. See this discussion

here is a sample code:

#include <iostream>
#include <unordered_map>
using namespace std;

void output(const auto& table)
{
   for (auto const & [k, v] : table)
   {
        std::cout << "Key: " << k << " Value: " << v << std::endl;
   }
}

int main() {
	std::unordered_map<string, int> mydata = {
		{"one", 1},
		{"two", 2},
		{"three", 3}
	};
	output(mydata);
	return 0;
}

Solution 6 - C++

it can even be done with a classic for loop.
advancing the iterator manually.

typedef std::map<int, int> Map;

Map mymap;

mymap['a']=50;
mymap['b']=100;
mymap['c']=150;
mymap['d']=200;

bool itexist = false;
int sizeMap = static_cast<int>(mymap.size());
auto it = mymap.begin();
for(int i = 0; i < sizeMap; i++){
    std::cout << "Key: " << it->first << " Value: " << it->second << std::endl;
    it++;
}

Solution 7 - C++

if you just want to iterate over the content without changing values do:

for(const auto & variable_name : container_name(//here it is map name)){
    cout << variable_name.first << " : " << variable_name.second << endl; 
} 

If you want to modify the contents of the map, remove the const and keep & (if you want to modify directly the contents inside container). If you want to work with a copy of the container values, remove the & sign too; after that, you can access them by using .first and .second on "variable_name".

Solution 8 - C++

Other way :

map <int, string> myMap = {
	{ 1,"Hello" },
	{ 2,"stackOverflow" }
};
for (auto iter = cbegin(myMap); iter != cend(myMap); ++iter) {
	cout << iter->second << endl;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNoNameView Question on Stackoverflow
Solution 1 - C++P0WView Answer on Stackoverflow
Solution 2 - C++Vlad from MoscowView Answer on Stackoverflow
Solution 3 - C++ColumboView Answer on Stackoverflow
Solution 4 - C++John MutumaView Answer on Stackoverflow
Solution 5 - C++Mital VoraView Answer on Stackoverflow
Solution 6 - C++NaturalDemonView Answer on Stackoverflow
Solution 7 - C++Shantanu IngleView Answer on Stackoverflow
Solution 8 - C++N.OmarView Answer on Stackoverflow