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)
#include <iostream>
#include <map>
#include <sstream>
int digit_count(int number) {
int digits = 0;
if (number < 0) digits = 1; // remove this line if '-' counts as a digit
while (number) {
number /= 10;
digits++;
}
return digits;
}
int main() {
int v1, v2;
std::map< int, std::map< int, int> > m;
std::istringstream stm {"1 2 2 3 3 1 4 1 4 5 5 3 5 6 5 7 5 8 6 4 7 6 8 9 9 10"};
while (stm >> v1 >> v2) {
m[v1];
m[v1][v2] = 1;
}
std::cout << "Map layout " << "\n";
std::string ss = "";
int dc = digit_count(m.rbegin()->first); // equals max number
for (constauto & p : m) {
std::cout << p.first << ss.append(" ", (dc - digit_count(p.first))) << "| ";
for (constauto & val : p.second)
std::cout << val.first << " ";
ss = "";
std::cout << "\n";
}
int start {4};
std::cout << "\nStart : " << start << "\n";
std::cout << "Result : " << "\n";
// efficient loop
for (constauto & e : m[start])
std::cout << e.first << " ";
for (constauto & x : m[e.first]) // this line generates error
std::cout << x.first << " ";
std::cout << "\n";
return 0;
}
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 << " ";
}
}