snippetcppCritical
How to use range-based for() loop with std::map?
Viewed 0 times
withhowusestdforrangeloopbasedmap
Problem
The common example for C++11 range-based for() loops is always something simple like this:
In which case
When the container being traversed is something simple, it looks like range-based for() loops will give us each item, not an iterator. Which is nice...if it was iterator, first thing we'd always have to do is to dereference it anyway.
But I'm confused as to what to expect when it comes to things like maps and multimaps.
(I'm still on g++ 4.4, while range-based loops are in g++ 4.6+, so I haven't had the chance to try it yet.)
std::vector numbers = { 1, 2, 3, 4, 5, 6, 7 };
for ( auto xyz : numbers )
{
std::cout << xyz << std::endl;
}In which case
xyz is an int. But, what happens when we have something like a map? What is the type of the variable in this example:std::map testing = { /*...blah...*/ };
for ( auto abc : testing )
{
std::cout first << std::endl; // ? or is abc an iterator?
}When the container being traversed is something simple, it looks like range-based for() loops will give us each item, not an iterator. Which is nice...if it was iterator, first thing we'd always have to do is to dereference it anyway.
But I'm confused as to what to expect when it comes to things like maps and multimaps.
(I'm still on g++ 4.4, while range-based loops are in g++ 4.6+, so I haven't had the chance to try it yet.)
Solution
Each element of the container is a
or as
if you don't plan on modifying the values.
In C++11 and C++14, you can use enhanced
You could also consider marking the
map::value_type, which is a typedef for std::pair. Consequently, in C++17 or higher, you can writefor (auto& [key, value]: myMap) {
std::cout << key << " has value " << value << std::endl;
}or as
for (const auto& [key, value]: myMap) {
std::cout << key << " has value " << value << std::endl;
}if you don't plan on modifying the values.
In C++11 and C++14, you can use enhanced
for loops to extract out each pair on its own, then manually extract the keys and values:for (auto& kv : myMap) {
std::cout << kv.first << " has value " << kv.second << std::endl;
}You could also consider marking the
kv variable const if you want a read-only view of the values.Code Snippets
for (auto& [key, value]: myMap) {
std::cout << key << " has value " << value << std::endl;
}for (const auto& [key, value]: myMap) {
std::cout << key << " has value " << value << std::endl;
}for (auto& kv : myMap) {
std::cout << kv.first << " has value " << kv.second << std::endl;
}Context
Stack Overflow Q#6963894, score: 622
Revisions (0)
No revisions yet.