Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Shouldn't I Use vector<vector<vector<int>>>?

Tags:

c++

vector

I have just read a question regarding initializing multidimensional vectors (question) and Viktor Sehr and Sbi reccomended instead using a single vector and getting the element with my_vector[x+y*100+z*100*100]. Why is this? Is it for performance reasons? If so, how does it improve performance? Thanks in advance, ell.

Edit: Do these reasons still apply when the width/height/depth are not the same and can change?

like image 401
Ell Avatar asked Dec 09 '22 02:12

Ell


2 Answers

Just few reasons:

It wastes spaces, it is slow (unpredictable memory access, cache waste, etc), it's cumbersome

Main performance drawback is likely to be caching. With flat arrays you are guaranteed memory to be contiguous - cache is happy. With vector of vectors - who knows!

like image 120
Anycorn Avatar answered Dec 23 '22 19:12

Anycorn


This advice is sound if you're looking at a bottleneck here. If memory usage or speed of access of this vector are not critical, just go down the easiest road.

You should have a look at Boost.MultiArray which gives you best of both worlds.

If for whatever reason you cannot use Boost, I'd definitely typedef it:

typedef vector<vector<vector<int> > > My3DIntVector;

My3DIntVector v;
like image 35
Thomas Avatar answered Dec 23 '22 20:12

Thomas