# c++ vectors

This topic is 3443 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi all, I have a 3d vector declared in my header file that I would like to initiate in my cpp file. But when I do something like vector<vector<vector<int> > > main_vec(2, vector<vector<int> > (2, vector<int>(2, 0))) it's thinking I'm trying to access the function main_vec and denies me. I'm trying to switch over from arrays to vectors so I'm still a bit rusty on it, can anyone help? Mahalo

##### Share on other sites
you're better off using a single vector, and calculating the index:

vector<int> vec;
T& Value(x,y,z) { return vec[x + y * length + z * (length + width)] };

This is what c++ does under the hood anyway

##### Share on other sites
Your code works for me. You could default-construct the vector and then give it value with .assign().

Although, I also think that using one single vector and doing the indexing yourself is much better idea.

##### Share on other sites
Can you try and explain what you mean by a single vector and do the indexing by my self? I realized a 3d array is kind of complex for what I'm doing, so if there are better and simpler ways of doing it I'd like to learn it.

Mahalo

##### Share on other sites
Quote:
 Original post by AieaCan you try and explain what you mean by a single vector and do the indexing by my self? I realized a 3d array is kind of complex for what I'm doing, so if there are better and simpler ways of doing it I'd like to learn it.Mahalo

I mean what incin said. Use vector<int> and make a function that'll calculate the index from X, Y, Z coordinates.

##### Share on other sites
Ahh ok so you are saying to use a single array and just expand it so it looks like a multidimensional one.

Let me try that, thanks.

##### Share on other sites
A vector of vectors is not the same thing as a 2D vector (and the same for 3D) anyway. If what you want is the equivalent of a 2D or 3D array then a vector of vectors is not a good way to do it. A vector of vectors is more like an array of pointers to dynamically allocated arrays. The memory layout is very different from a multi dimensional array.

##### Share on other sites
If I understand what you're doing, the vector in the header is global and is default constructed before int main (). Somewhere after int main() you are using the wrong syntax to assign content to your already constructed vector. This will probably work for you

main_vec = vector<vector<vector<int> > >(2, vector<vector<int> > (2, vector<int>(2, 0)));

std::vectors are useful because they are dynamically sized. If all you want is constant data in a header, then this may not be the best time to replace your arrays with vectors. It might be a good time to examine why you have this constant data in a header.

Also, try a boost::multi_array.