Two dimensional vector (or 2D vector) in C++ represents a table like structure that has two dimensions, row and column. It is, in fact, a standard STL vector of type vector. Vectors can be nested up to any depth. Here we’ll use two level nesting for two dimensions.
Initialization
We can initialize the values of all the elements of a 2D vector in time of declaration.
#include<iostream>
#include<vector>
using namespace std;
int main() {
vector<vector<int>> v2d {{1, 2, 3}, {3, 4, 6}, {7, 8, 9}};
for (auto v : v2d) {
for (auto v1 : v) {
cout << v1 << " ";
}
cout << endl;
}
cout << endl;
}
$ c++ -o test test.cpp
$ ./test
1 2 3
3 4 6
7 8 9
We declared the 2D vector as vector of integer vectors. The internal vector represents a series (array) of integers. And the outer vector represents a series of internal vector. In this example, we initialized a 3×3 vector. One thing to note here is that the size of all the internal vectors does not need to be the same. You can try that out.
We also traversed the 2d vector and printed all the elements.
Adding Elements
In the previous example, we initialized the vector with all the elements. Instead, we could have created an empty vector and them added elements later on. Each element of the 2D vector will again be a vector.
#include<iostream>
#include<vector>
using namespace std;
int main() {
vector<vector<int>> v2d;
v2d.push_back({1, 2, 3});
v2d.push_back({4, 5, 6});
v2d.push_back({7, 8, 9});
for (auto v : v2d) {
for (auto v1 : v) {
cout << v1 << " ";
}
cout << endl;
}
cout << endl;
}
Output of this program will exactly be the same as the previous one.
Two Dimensional Vector of Fixed Size
We can also fix the number of rows and columns in time of 2D vector initialization.
#include<iostream>
#include<vector>
using namespace std;
int main() {
int row = 3, col = 4;
vector<vector<int>> v2d(row, vector<int>(col, 0));
v2d[0][0] = 1;
v2d[0][1] = 2;
v2d[0][2] = 3;
v2d[0][3] = 4;
for (auto v : v2d) {
for (auto v1 : v) {
cout << v1 << " ";
}
cout << endl;
}
cout << endl;
}
We initialized the vector for 3 rows and 4 columns. All values are initialized as 0. Then we changed all 4 columns of the first row.
$ c++ -o test test.cpp
$ ./test
1 2 3 4
0 0 0 0
0 0 0 0
We can see the changed values for the first row and default values for others.