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 vec开发者_开发知识库tor 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.
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.
See if boost::multi array could help, it can do things like:
typedef boost::multi_array<int, 3> array_type;
array_type::extent_gen extents;
array_type A(extents[3][3][3]);
A[0][0][0] = 4;
A[2][2][2] = 5;
A.resize(extents[2][3][4]);
assert(A[0][0][0] == 4);
// A[2][2][2] is no longer valid.
Here is the link : http://www.boost.org/doc/libs/1_47_0/libs/multi_array/doc/user.html#sec_example
If you're on Linux, check the code with valgrind. If there's a memory error in your code (which sounds like what you're encountering), valgrind should expose it.
精彩评论