A common question from the SO archives:
C++11: How to use range-based
for
loop withstd::map
?The common example for C++0x 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 anint
. But, what happens when we have something like amap
? 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
map
s andmultimap
s.
Add a Comment
Comments are closed.