Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Loop through Map

Tags:

c++

dictionary

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?          } } 
like image 579
NoName Avatar asked Oct 09 '14 15:10

NoName


People also ask

How do I iterate a map automatically?

The simplest way to iterate through a map is to use the range-based for loop (introduced in C++11) along with the auto keyword. The auto keyword directs the compiler to deduce the type of the variable which makes the code more robust and simple.

Can we iterate HashMap?

In Java HashMap, we can iterate through its keys, values, and key/value mappings.


2 Answers

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; } 
like image 127
P0W Avatar answered Oct 13 '22 21:10

P0W


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 ); 
like image 25
Vlad from Moscow Avatar answered Oct 13 '22 21:10

Vlad from Moscow