The common example for C++11 range-based for() loops is always something simple like this:
std::vector<int> 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< foo, bar > testing = { /*...blah...*/ };
for ( auto abc : testing )
{
std::cout << abc << std::endl; // ? should this give a foo? a bar?
std::cout << abc->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.)
This question is related to
c++
c++11
for-loop
dictionary
From this paper: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2049.pdf
for( type-speci?er-seq simple-declarator : expression ) statement
is syntactically equivalent to
{
typedef decltype(expression) C;
auto&& rng(expression);
for (auto begin(std::For<C>::begin(rng)), end(std::For<C>::end(rng)); begin != end; ++ begin) {
type-speci?er-seq simple-declarator(*begin);
statement
}
}
So you can clearly see that what is abc
in your case will be std::pair<key_type, value_type >
.
So for printing you can do access each element by abc.first
and abc.second
In C++17 this is called structured bindings, which allows for the following:
std::map< foo, bar > testing = { /*...blah...*/ };
for ( const auto& [ k, v ] : testing )
{
std::cout << k << "=" << v << "\n";
}
If you only want to see the keys/values from your map and like using boost, you can use the boost adaptors with the range based loops:
for (const auto& value : myMap | boost::adaptors::map_values)
{
std::cout << value << std::endl;
}
there is an equivalent boost::adaptors::key_values
If copy assignment operator of foo and bar is cheap (eg. int, char, pointer etc), you can do the following:
foo f; bar b;
BOOST_FOREACH(boost::tie(f,b),testing)
{
cout << "Foo is " << f << " Bar is " << b;
}
Source: Stackoverflow.com