Initializing a two dimensional std::vector

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

std::vector<std::vector<int> > fog(
    ROW_COUNT,
    std::vector<int>(COLUMN_COUNT)); // 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(
    ROW_COUNT,
    std::vector<int>(COLUMN_COUNT, 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 } };
                           

Leave a Comment