How do I turn std::map to repeat?

Asked 2 years ago, Updated 2 years ago, 81 views

std::map< std::string, std::map<std::string, std::string> > My brother

m["name1"]["value1"] = "data1";
m["name1"]["value2"] = "data2";
m["name2"]["value1"] = "data1";
m["name2"]["value2"] = "data2";
m["name3"]["value1"] = "data1";
m["name3"]["value2"] = "data2";

and

How do I turn for name1 to name3?

loops c++ for-loop dictionary

2022-09-21 17:56

1 Answers

in the iterator

You have to write two for statements like this.

int main(){
    std::map< std::string, std::map<std::string, std::string> > m;
    m["name1"]["value1"] = "data1";
    m["name1"]["value2"] = "data2";
    m["name2"]["value1"] = "data1";
    m["name2"]["value2"] = "data2";
    m["name3"]["value1"] = "data1";
    m["name3"]["value2"] = "data2";


    typedef std::map<std::string, std::map<std::string, std::string>>::iterator outmap;
    //Etterate the first map
    for(outmap iterator1 = m.begin(); iterator1 != m.end(); iterator1++) {
        cout << iterator1->first << endl;

        typedef std::map<std::string, std::string>::iterator inmap;
        //2 Eterate the second map
        for(inmap iterator2 = (iterator1->second).begin(); iterator2!=(iterator1->second).end(); iterator2++ ){
            cout << iterator2->first << " " << iterator2->second << endl;
        }
    }
}

Result:

name1
value1 data1
value2 data2
name2
value1 data1
value2 data2
name3
value1 data1
value2 data2


2022-09-21 17:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.