Monthly Archives: January 2021

C++ – Initialize a two-dimensional vector in C++

1. init two-dimensional with 0 and resize

1
2
3
4
5
6
7
8
9
vector<vector<int>> c(n, vector<int>(m, 0));
 
resize:
// instantiate vector object of type std::vector<int>
std::vector<std::vector<int>> matrix;
 
// resize the vector to M elements of type std::vector<int>,
// each having size N and given default value
matrix.resize(M, std::vector<int>(N, default_value));

2. init with default value

1
2
3
4
5
6
vector<vector<int>> accounts
    {
        {1, 5},
        {7, 3},
        {3, 5}
    };