Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initializing a vector of vector<doubles> c++

Tags:

c++

vector

Hi I want to initialize a size 9 vector whose elements are vectors of the size, say 5. I want to initialize all the elements to the zero vector.

Is this way correct?

vector<double> z(5,0);

vector< vector<double> > diff(9, z);

OR is there a shorter way to do this?

like image 615
smilingbuddha Avatar asked Sep 22 '11 17:09

smilingbuddha


People also ask

Are vectors initialized to zero C++?

The default value of a vector is 0. Syntax: // For declaring vector v1(size); // For Vector with default value 0 vector v1(5);


2 Answers

You could potentially do this in a single line:

vector<vector<double> > diff(9, vector<double>(5));

You might also want to consider using boost::multi_array for more efficient storage and access (it avoids double pointer indirection).

like image 105
bdonlan Avatar answered Oct 17 '22 06:10

bdonlan


You can put it all in one line:

vector<vector<double>> diff(9, vector<double>(5));

This avoids the unused local variable.

(In pre-C++11 compilers you need to leave a space, > >.)

like image 26
Kerrek SB Avatar answered Oct 17 '22 07:10

Kerrek SB