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? } }
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.
In Java HashMap, we can iterate through its keys, values, and key/value mappings.
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; }
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With