Rella
Rella

Reputation: 66965

How to fill `std::vector<std::vector<T> >` with default values?

So I try this:

std::vector< std::vector<int> > matrix(4);

matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3;
matrix[0][3] = 1;

matrix[1][0] = 1;
matrix[1][1] = 2;
matrix[1][2] = 3;
matrix[1][3] = 1;

matrix[2][0] = 1;
matrix[2][1] = 2;
matrix[2][2] = 3;
matrix[2][3] = 1;

matrix[3][0] = 1;
matrix[3][1] = 2;
matrix[3][2] = 3;
matrix[3][3] = 1;

But something goes wrong and my app dies at runtime=( What to do? How to embed values into vector of vectors correctly?

Upvotes: 5

Views: 5571

Answers (2)

justin
justin

Reputation: 104698

In this case, you can take Björn's approach one step farther and fully initialize the 2D vector as you outlined with the values you supplied:

std::vector<int> tmp(4,0); 
tmp[0] = 1;
tmp[1] = 2;
tmp[2] = 3;
tmp[3] = 1;

std::vector< std::vector<int> > matrix(4, tmp);

One could simply have written it as:

std::vector<int> tmp(4,1); 
tmp[1] = 2;
tmp[2] = 3;

std::vector< std::vector<int> > matrix(4, tmp);

but I often favor the first for clarity.

Upvotes: 2

Bj&#246;rn Pollex
Bj&#246;rn Pollex

Reputation: 76856

Use this:

std::vector< std::vector<int> > matrix(4, std::vector<int>(4));

This initializes your outer vector with 4 copies of std::vector<int>(4).

Upvotes: 11

Related Questions