简体   繁体   中英

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?

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) .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM