In this C++ tutorial, you shall learn about vector of vectors, how to create vector of vectors, and traverse the inner vectors using For loop, with example programs.
Vector of Vectors in C++
Vector of vectors is a vector in which each element is a vector of elements.
To create a vector of vectors, we need to specify the datatype of element as vector<>
, and specify vectors as elements, as shown in the following.
</>
Copy
//int vectors
vector<int> v1 { 1, 3, 5, 7, 9 };
vector<int> v2 { 2, 4, 6, 8, 10 };
//vector of vectors
vector<vector<int>> vv = {v1, v2};
Examples
1. Vector of Integer Vectors
In the following program, we take two integer vectors in v1
and v2
, and use them to create a vector of integer vectors vv
.
main.cpp
</>
Copy
#include <iostream>
#include <vector>
using namespace std;
int main() {
//int vectors
vector<int> v1 { 1, 3, 5, 7, 9 };
vector<int> v2 { 2, 4, 6, 8, 10 };
//vector of vectors
vector<vector<int>> vv = {v1, v2};
//iterate over vector elements
for (auto& tempVector : vv) {
for (auto& element : tempVector) {
cout << element << " ";
}
cout << endl;
}
}
Output
1 3 5 7 9
2 4 6 8 10
Conclusion
In this C++ Tutorial, we learned how to define a vector of vectors, and how to traverse through individual elements of the inner vectors.