Initializing a two dimensional std::vector

Ferenc Deak picture Ferenc Deak · Jul 15, 2013 · Viewed 233.9k times · Source

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?

Answer

hmjd picture hmjd · Jul 15, 2013

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 than 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 was 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 } };