C++11 range-based for and map : readability
c++, c++11, code-readability, dictionary, foreach
Solution
There is no such thing as you want. The closest is to declare variables inside the loop:
for (auto& FooAndAssociatedBar : FooAndAssociatedBars) {
auto& foo = FooAndAssociatedBar.first;
auto& bar = FooAndAssociatedBar.second;
// ...
}
Problem
The new range-based for loops really improve readability and are really easy to use. However, consider the following : ``` map<Foo,Bar> FooAndAssociatedBars; for (auto& FooAndAssociatedBar : FooAndAssociatedBars) { FooAndAssociatedBar.first.doSth(); FooAndAssociatedBar.second.doSomeOtherThing(); } ``` It may be a detail but I find it would have been more readable if I could have done something like : ``` for ( (auto& foo, auto& bar) : FooAndAssociatedBars) { foo.doSth(); bar.doSomeOtherThing(); } ``` Do you know an equivalent syntax ? EDIT: Good news: C++17 has a proposal that adresses this problem, called structured bindings (see 1). In C++17, you should be able to write: ``` tuple<T1,T2,T3> f(/*...*/) { /*...*/ return {a,b,c}; } auto [x,y,z] = f(); // x has type T1, y has type T2, z has type T3 ``` which solves this readability problem