Last Updated on 2022-04-21 by Clay
When we are programming with C++ and we want to store some data, in addition to use the array, we use the "vector" in the standard library.
However, not all data are purely one-dimensional data, sometimes we may have the need to create two-dimensional or even higher-dimensional initialization data.
The article is a note to record how to do that.
There are roughly the following methods:
- Initialize on declaration (applies to C++11 and later)
- push_back()
- resize()
- constructor
Initialize on declaration
#include <iostream>
#include <vector>
using namespace std;
int main() {
// Init
vector<vector<int>> matrix {
{1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3}
};
// Print
for (auto row: matrix) {
for (auto val: row) {
printf("%d ", val);
}
printf("\n");
}
return 0;
}
Output:
1 1 1 1
2 2 2 2
3 3 3 3
It is basically the same as the original declaration of one-dimensional, that is, the form of declaration of two-dimensional is changed. However, this should pay attention to the version restrictions of C++, at least C++11 will support this method.
push_back()
Simply and rudely, pass them into the vector one by one.
#include <iostream>
#include <vector>
using namespace std;
int main() {
// Settints
int m = 3;
int n = 4;
// Init
vector<vector<int>> matrix;
for (int i=0; i<m; ++i) {
vector<int> row;
for (int j=0; j<n; ++j) {
row.push_back(i+1);
}
matrix.push_back(row);
};
// Print
for (auto row: matrix) {
for (auto val: row) {
printf("%d ", val);
}
printf("\n");
}
return 0;
}
Output:
1 1 1 1
2 2 2 2
3 3 3 3
resize()
resize()
is a method used in a vector to resize a specific size, and we can also use it to set the initial value together.
#include <iostream>
#include <vector>
using namespace std;
int main() {
// Settints
int m = 3;
int n = 4;
// Init
vector<vector<int>> matrix(m);
for (int i=0; i<m; ++i) {
matrix[i].resize(n, i+1);
};
// Print
for (auto row: matrix) {
for (auto val: row) {
printf("%d ", val);
}
printf("\n");
}
return 0;
}
Output:
1 1 1 1
2 2 2 2
3 3 3 3
It feels like this method is more concise than push_back(). But I prefer constructor method.
Constructor
This should be the most recommended simple method, and only needs one line to complete the initialization. The only problem is that it can only initialize the same value, and it cannot be set by row or even as detailed as the above example.
There are pros and cons.
#include <iostream>
#include <vector>
using namespace std;
int main() {
// Settints
int m = 3;
int n = 4;
// Init
vector<vector<int>> matrix(m, vector<int>(n, 1));
// Print
for (auto row: matrix) {
for (auto val: row) {
printf("%d ", val);
}
printf("\n");
}
return 0;
}
Output:
1 1 1 1
1 1 1 1
1 1 1 1