user1362058 user1362058 - 2 months ago 14
C++ Question

How to print a nested map-map-vector

I am having issues loading and printing my map-map-vector data structure. I think it's on the printing side, since I am not 100% sure how to use iterators.

I created and loaded the data into the structure to store my data here:
(I created inner_test and myvector because it looked like I needed them for the iterators. I'm not sure how the iterators know that inner_test and myvector are part of test though.)

map<int, map<string, vector<string>>> test;
map<string, vector<string>> inner_test;
vector<string> myvector;

ifstream thisfile;
const char *file1 = argv[1];;
string filler;

while( thisfile >> filler ){
string sortedFiller = filler;
sort(sortedFiller.begin(), sortedFiller.end());

I tried to print it with this, but I don't think I quite understand what I'm doing here.

map<int, map<string, vector<string>>>::iterator itr1;
map<string, vector<string>>::iterator itr2;
vector<string>::iterator itr3;

for(itr1 = test.begin(); itr1 != test.end(); itr1++){
cout << itr1->first;
for(itr2 = inner_test.begin(); itr2 != inner_test.end(); itr2++){
cout << itr2->first;
for(itr3 = myVector.begin(); itr3 != myVector.end(); itr3++){
cout << *itr3;
cout << endl;


Your inner_test, and my_vector variables are empty containers, and are unrelated to the actual std::map, you want to print, in any way. This is one of the examples how can you print multidimensional container:

    // auto type automatically defines itself as a return type of test.begin ()
for(auto itr1 = test.begin(); itr1 != test.end(); itr1++)
    cout << itr1->first << ' '; // Add space to separate entries on the same line
    // itr1->second represents map<string, vector<string>> stored in test.
    for(auto itr2 = itr1->second.begin (); itr2 != itr1->second.end (); itr2++)
        cout << itr2->first << ' ';
        // itr2->second represents vector<string> stored in map<string, vector<string>> which is stored in test.
        for(auto itr3 = itr2->second.begin(); itr3 != itr2->second.end(); itr3++)
            cout << *itr3 << ' ';
    cout << endl;