Nested Vectors

Besides basic data types, we can also insert other vectors into vectors. We call these inserted vectors nested vectors.

Nested vectors allow us to store more complex data structures. Let's look at an example:

std::vector<std::vector<std::string>> studyGroups = {{"Anna", "Boris"}, {"David", "Eva"}};

In this example, we have a vector studyGroups that contains two other vectors, each representing one study group.

Access to individual elements in a nested vector works similarly to a one-dimensional vector. For example:

// Print a specific student
std::cout << studyGroups[0][1];  // Prints: Boris

When we want a value from this vector, we just add square brackets with the index of the nested vector: studyGroups[0][1]. This first selects the element at index 0 of the studyGroups vector, which is {"Anna", "Boris"}, and in this element we select the element at index 1, which is "Boris".

Instructions

Print from the vector teammates in the second group (index 1) the first teammate (index 0).

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

8/10

Nested Vectors | Start Coder