Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prefill a std::vector at initialization?

Tags:

c++

stdvector

I want to create a vector of vector of a vector of double and want it to already have (32,32,16) elements, without manually pushing all of these back. Is there a way to do it during initialization? (I don't care what value gets pushed).

I want a 3-dimensional array, the first dimension has 32, the second dimension has 32 and the third dimension has 16 elements.

like image 937
jmasterx Avatar asked Jun 08 '10 15:06

jmasterx


People also ask

How do you declare a vector by default value?

Specifying a default value for the Vector: In order to do so, below is the approach: Syntax: // For declaring vector v(size, default_value); // For Vector with a specific default value // here 5 is the size of the vector // and 10 is the default value vector v1(5, 10);


2 Answers

One liner:

std::vector< std::vector< std::vector<double> > > values(32, std::vector< std::vector<double> >(32, std::vector<double>(16, 0.0)));

Or breaking the lines:

typedef std::vector<double> v_type;
typedef std::vector<v_type> vv_type;
typedef std::vector<vv_type> vvv_type;

vvv_type values(32, vv_type(32, v_type(16, 0.0)));

I would remark that this allocate a fair lot of objects (32*32*16).

Would a single vector work ?

std::vector<double> values(32*32*16, 0.0)

That would be 32*32*16-1 less new.

like image 71
Matthieu M. Avatar answered Oct 07 '22 23:10

Matthieu M.


One of the ctors for a vector allows you to specify both the size and a value to be copied into the elements for the vector. I'm not quite sure what you means by "(32,32,16)" elements, but you could do something like:

// create a vector containing 16 elements set to 2
std::vector<int> temp(16, 2);   

// create a vector of 32 vectors, each with 16 elements set to 2
std::vector<std::vector<int> > values(32, temp);
like image 31
Jerry Coffin Avatar answered Oct 07 '22 22:10

Jerry Coffin