Can anybody suggest how to efficiently loop over so that, given a start of say 4, the result would be 1(1), 2(2), 5(1), 3(2), 6(2), 7(2), 8(2), 9(3), 10(4)
I get the following error however, when the inner map key (second) is used as a key for the outer map.
1 2 3 4 5 6
g++ -g -Wall -std=c++14 -o "efficient_loop_over_map""efficient_loop_over_map.cpp" (in directory: /c++/learn)
efficient_loop_over_map.cpp: In function ‘int main()’:
efficient_loop_over_map.cpp:46:29: error: ‘e’ was not declared in this scope
for (constauto & x : m[e.first])
^
Compilation failed.
The reason you get an error message is because the loop on line 46-47 is not part of the loop on line 44-45. If you want a loop to contain multiple statements you need to use curly brackets (personally I always use them even when not necessary).
1 2 3 4 5 6 7 8
for (constauto & e : m[start])
{
std::cout << e.first << " ";
for (constauto & x : m[e.first])
{
std::cout << x.first << " ";
}
}