Nested Vectors
An element of a vector can be another vector. A vector inside a vector is called a nested vector. Nested vectors are useful for data that forms groups, such as study groups:
std::vector<std::vector<std::string>> studyGroups = {{"Jennifer", "Boris"}, {"David", "Ava", "Nancy"}};Read the type from the outside in: studyGroups is a vector whose elements are of type std::vector<std::string>, that is, vectors of texts. That's why the type ends with two angle brackets >> in a row: the first one closes the inner std::vector<std::string>, the second one the outer vector. Each inner vector has its own curly braces, and a comma separates it from the next one.
The vector studyGroups has two elements, and each of them is one group. You get a single student with two indexes. studyGroups[1][0] first takes the element at index 1 (the second group, {"David", "Ava", "Nancy"}) and then the element at index 0 of that vector:
std::cout << studyGroups[1][0] << std::endl;This prints:
DavidEverything you know about vectors works for the inner vectors too. studyGroups.size() is 2, the number of groups, while studyGroups[1].size() is 3, the number of students in the second group. So the inner vectors can have different lengths. The call studyGroups[0].push_back("Tom") adds Tom to the end of the first group:
studyGroups[0].push_back("Tom");
std::cout << studyGroups.size() << " " << studyGroups[0].size() << std::endl;
std::cout << studyGroups[0][2] << std::endl;This prints:
2 3
TomYou can't print a whole inner vector at once either: std::cout << studyGroups[1]; ends with the same error as printing a whole vector. Print single elements.
Instructions
- 1
Print the first member of the second team. Use two indexes. The output should include the line
Daniel. - 2
Adam has joined the first team. Add
"Adam"to the end of the first team,teams[0], withpush_back(). - 3
Print the number of members of the first team and its last member, one below the other. The output should include the lines
Members: 3andLast: Adam.