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.
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);
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
.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With