Iterate over a map in C++
This post will discuss how to iterate over a map in C++.
The std::begin and std::end function returns an iterator pointing to the first element and the one-past-the-last element in the sequence. We can iterate over a map that starts with std::begin and ends at std::end, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <map> #include <string> int main() { std::map<std::string, int> map = { {"one", 1}, {"two", 2}, {"three", 3} }; for (auto it = map.begin(); it != map.end(); it++) { std::cout << "{" << it->first << ", " << it->second << "}" << std::endl; } return 0; } |
Output:
{one, 1}
{three, 3}
{two, 2}
We can also use the range-based for-loop over the iterator-based for-loop.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <map> #include <string> int main() { std::map<std::string, int> map = { {"one", 1}, {"two", 2}, {"three", 3} }; for (const auto &entry: map) { std::cout << "{" << entry.first << ", " << entry.second << "}" << std::endl; } return 0; } |
Output:
{one, 1}
{three, 3}
{two, 2}
Starting with C++17, consider using the range-based for-loop with structured bindings:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <map> #include <string> int main() { std::map<std::string, int> map = { {"one", 1}, {"two", 2}, {"three", 3} }; for (auto const& [key, val] : map) { std::cout << "{" << key << ", " << val << "}" << std::endl; } return 0; } |
Output:
{one, 1}
{three, 3}
{two, 2}
To iterate over the map in reverse order, consider using the range-based for-loop with a reverse adapter offered by the boost library:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <map> #include <boost/range/adaptor/reversed.hpp> int main() { std::map<std::string, int> map = { {"one", 1}, {"two", 2}, {"three", 3} }; for (const auto &entry: boost::adaptors::reverse(map)) { std::cout << "{" << entry.first << ", " << entry.second << "}" << std::endl; } return 0; } |
Output:
{two, 2}
{three, 3}
{one, 1}
This is equivalent to the following code using reverse iterators:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <map> #include <boost/range/adaptor/reversed.hpp> int main() { std::map<std::string, int> map = { {"one", 1}, {"two", 2}, {"three", 3} }; for (auto it = map.rbegin(); it != map.rend(); it++) { std::cout << "{" << it->first << ", " << it->second << "}" << std::endl; } return 0; } |
Output:
{two, 2}
{three, 3}
{one, 1}
That’s all about iterating over a map in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)