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.
EDIT: This is what I wound up with, using our internal definitions of String, VariantMap, VariantList, Variant (hopefully they map closely to standard Variant, VariantMap, VariantList, but I'm not sure if it does or not):
//Collin
VariantMap familyInfo0;
familyInfo0[String("%type")] = Variant("nuclear");
familyInfo0[String("%parent")] = Variant("single");
familyInfo0[String("#text")] = Variant("3");
VariantMap studentInfo0;
studentInfo0[String("name")] = Variant("Collin");
studentInfo0[String("average")] = Variant("100");
studentInfo0[String("family")] = familyInfo0;
VariantMap classInfo;
VariantList students;
VariantMap studentMap0;
studentMap0[String("student")] = studentInfo0;
VariantMap studentMap1;
studentMap1[String("student")] = studentInfo1;
students.push_back(studentMap0);
students.push_back(studentMap1);
classInfo[String("class")] = students;
Variant student0Name = classInfo[String("class")].cast<VariantList>()[0].cast<VariantMap>()[String("name")];
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)