Initializing a two dimensional std::vector

2019-01-07 03:54发布

问题:

So, I have the following:

std::vector< std::vector <int> > fog;

and I am initializing it very naively like:

    for(int i=0; i<A_NUMBER; i++)
    {
            std::vector <int> fogRow;
            for(int j=0; j<OTHER_NUMBER; j++)
            {
                 fogRow.push_back( 0 );
            }
            fog.push_back(fogRow);
    }

And it feels very wrong... Is there another way of initializing a vector like this?

回答1:

Use the std::vector::vector(count, value) constructor that accepts an initial size and a default value:

std::vector<std::vector<int> > fog(
    A_NUMBER,
    std::vector<int>(OTHER_NUMBER)); // Defaults to zero initial value

If a value other zero, say 4 for example, was required to be the default then:

std::vector<std::vector<int> > fog(
    A_NUMBER,
    std::vector<int>(OTHER_NUMBER, 4));

I should also mention uniform initialization is introduced in C++11, which permits the initialization of vector, and other containers, using {}:

std::vector<std::vector<int> > fog { { 1, 1, 1 },
                                    { 2, 2, 2 } };


回答2:

There is no append method in std::vector, but if you want to make a vector containing A_NUMBER vectors of int, each of those containing other_number zeros, then you can do this:

std::vector<std::vector<int>> fog(A_NUMBER, std::vector<int>(OTHER_NUMBER));


回答3:

Let's say you want to initialize 2D vector, m*n, with initial value to be 0

we could do this

#include<iostream>
int main(){ 
    int m = 2, n = 5;

    vector<vector<int>> vec(m, vector<int> (n, 0));

    return 0;
}


回答4:

The general syntax, as depicted already is:

std::vector<std::vector<int> > v (A_NUMBER, std::vector <int> (OTHER_NUMBER, DEFAULT_VALUE))  

Here, the vector 'v' can be visualised as a two dimensional array, with 'A_NUMBER' of rows, with 'OTHER_NUMBER' of columns with their initial value set to 'DEFAULT_VALUE'.

Also it can be written like this:

std::vector <int> line(OTHER_NUMBER, DEFAULT_VALUE)
std::vector<std::vector<int> > v(A_NUMBER, line)

Inputting values in a 2-D vector is similar to inputting values in a 2-D array:

for(int i = 0; i < A_NUMBER; i++) {
     for(int j = 0; j < OTHER_NUMBER; j++) {
         std::cin >> v[i][j]
     }
}

Examples have already been stated in other answers....!



标签: c++ vector