Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

std

stl

vector

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?

like image 869
Rella Avatar asked Nov 11 '11 11:11

Rella


1 Answers

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

like image 66
Björn Pollex Avatar answered Oct 01 '22 04:10

Björn Pollex