Why shouldn't I use the vector <vector <vector <int> >>?

I just read the question about initializing multidimensional vectors ( question ), and Victor Ser and Sbi recommended using a single vector instead 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 this increase productivity? Thanks in advance, ell.

Edit: Do these reasons apply when the width / height / depth does not match and can change?

+4
source share
4 answers

Just a few reasons:

It kills spaces, it is slow (unpredictable memory access, cache waste, etc.), it is cumbersome

The main performance drawback may be caching. When using flat arrays you are guaranteed to save memory - the cache is happy. With a vector of vectors - who knows!

+8
source

This tip sounds if you are looking at a bottleneck here. If memory usage or access speed to this vector is not critical, just follow the easiest road.

You should take a look at Boost.MultiArray , which gives you the best of both worlds.

If for some reason you cannot use Boost, I definitely typedef this:

 typedef vector<vector<vector<int> > > My3DIntVector; My3DIntVector v; 
+4
source

... Victor Ser and Sbi recommended using a single vector instead and getting the element with my_vector [x + y * 100 + z * 100 * 100]. Why is this?

Given the size, this is a logical recommendation if the size is fixed.

Is it for performance reasons? If so, how to increase productivity?

Consider:

  • number of distributions needed to create all arrays
  • copying time of even one measurement
  • the complexity that he adds to the system distributor
  • time required for free
  • complexity of general operations such as filling

Edit: Do these reasons apply when the width / height / depth does not match and can change?

Resizing an array (massive!) Can be very slow. You must understand how your program will work if you want it to be the fastest. In addition, the complexity of copying and destroying elements is also considered (when using something more complex than int ). If you do a lot of resizing or inserting / deleting, then a flattened vector can be very slow.

However, if its dimensions are fixed, you can do much better than std::vector . std::array is one of the alternatives. (If you are following the std::array route, be careful what you allocated on the stack)

+2
source

The only thing I can imagine is that it is one large block of memory and thus prevents fragmented memory. It is much easier to cache.

A vector<vector<vector<int> > > contains many pieces of memory: a piece for the first vector, a piece for each element in vector<> and a piece for each element in vector<vector<>> . This is not easy to cache and can lead to hardly predictable memory usage.

0
source

Source: https://habr.com/ru/post/1394747/


All Articles