Michele Michele - 1 year ago 38
C++ Question

How to retrieve string of keys out of nested map at same time

I have a nested

std::map
of student info that looks like this:

{
"class":[
"student":{
"name":"Collin",
"average":"100",
"family":{
"%type":"nuclear",
"%parent":"divorced",
"#text":"3"
} //family
} //student
"student":{
"name":"Jamie",
"average":"95",
"family":{
"%type":"nuclear",
"%parent":"single",
"#text":"2"
} //family
} //student
] //class
}//overall Map

where(above) - {} represents a Map
- [] represents a List


I'm trying to retrieve the info like this:

std::string student0Name = l_mapClassOfStudents[std::string("class")][std::string("student")][0][std::string("name")]; //see error message about operator for [ before student


However, I'm getting no operator [] matches these operands. This is at the [ right before student in the line above.

I saw this list inside map, but it doesn't say how to get items out.

Answer Source

If the students are in a list, use front() to retrieve the first element:

std::string student0Name = l_mapClassOfStudents[std::string("class")].front()[std::string("name")];

I think a better structure would be something like

typedef map<string,string> Student;
typedef list<Student> Class;
typedef list<Class> School;

Lists are usually used for iterating through. Alternatively you could use vector instead of list to access them by number:

typedef map<string,string> Student;
typedef vector<Student> Class;
typedef vector<Class> School;
cout << thisSchool[3][2]["name"]; // name of the 3rd student in the 4th class, if thisSchool is of type School (and enough classes and students exist)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download