Search code examples
c++vector3dvariable-assignmentdynamic-memory-allocation

C++ dynamic (multi-stage) 3D vector instantiation and element assignment


Okay, so I need to create a 3D data-structure at run-time, I decided to use std::vector, the problem is as follows: I know the dimension of the 1st dimension at instantiation time (when I create the object I'm using it in), but I don't know the dimension of the second until run-time, and the size of 3rd dimensions can vary. I have created the 3D vector and the run-time doesn't complain, however I'm having difficulty assigning values to the elements.

This code is part of an object I'm creating. In the class definition I have:

std::vector< std::vector< std::vector<double> > > splits;

Then in the object constructor, in order to create/allocate the first dimension, I have:

for(int i=0; i<sizeOfDimOne; i++){ //create 1st dimension
    splits.push_back( std::vector< std::vector<double> >() );
}

based on user input I need to create 2nd dimension of a certain size, I call a method for this:

for(int i=0; i<sizeOfDimOne; i++){
    for(int j=0; j<sizeOfDimTwo; j++) //create second dimension
        splits[i].push_back( std::vector<double>() );
}

However, when I get to assigning values:

for(int i=0; i<sizeOfDimThree; i++){
   splits[dim1][dim2].push_back( someValue ); //adding an element to the 3rd dim
}

(The someValue changes constantly (and is a double), and you don't have to worry about lower dimension indexing, everything checks out.) The problem is - when I checked splits[dim1][dim2][i] the value was 0.0 for (presumably all) entries, naturally this is not what was provided by someValue.

I have also tried creating the 3rd dimension using .resize(sizeOfDimThree) and then assigning using

splits[dim1][dim2][i] = whatever;

but that didn't work at all - no object/element was created at all.

I realize this perhaps isn't the most straight forward manner of phrasing the question, but I believe it is the most accurate, as there might be multiple-points of failure.


Solution

  • Okay, so it turns out, that technically everything was correct (albeit inefficient, which I got around by using .resize() for appropriate dimensions in turn), my 'problem' was (as it tends to be) a very stupid mistake, to verify that everything was assigned I used:

    printf("value assigned: %d", splits[dim1][dim2][dim3]);
    

    instead of (since splits is a double):

    printf("value assigned: %.3f", splits[dim1][dim2][dim3]);
    

    Moral of the story: pay attention to how you treat the variable datatype & post full source code.