c++ vectors

Started by
6 comments, last by Cantos 15 years, 8 months ago
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
Mahalo,AieaLove them semicolons and equal signs...
Advertisement
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
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.
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
Mahalo,AieaLove them semicolons and equal signs...
Quote:Original post by Aiea
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


I mean what incin said. Use vector<int> and make a function that'll calculate the index from X, Y, Z coordinates.
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.
Mahalo,AieaLove them semicolons and equal signs...
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.

Game Programming Blog: www.mattnewport.com/blog

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.

This topic is closed to new replies.

Advertisement