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?
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!
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With