Vector of vectors, reserve

巧了我就是萌 提交于 2019-11-29 05:29:30

Since your inner dimension is constant, I think you want

std::vector< std::array<int, 5> > vecs;
vecs.reserve(N);

This will give you preallocated contiguous storage, which is optimal for performance.

The size of the inner vectors is completely irrelevant for resizing the outer vector. There are no locality guarantees for your bundle of vectors, the locality guarantee (i.e. contiguous block in memory) exists for a single vector only.

Remember that a vector object itself has constant sizeof-size, its actual data is usually dynamically allocated. The outer vector, to first approximation, is a contiguous block of N 'pointers' to the inner vectors. Your reserve call does not reserve memory for possible elements of inner vectors, but only for the inner vector objects themselves (i.e. their bookkeeping data and their pointers to their dynamically allocated data block).

The inner vectors are initialized with the default constructor. So if you write:

vector<vector<int> > vecs;
vecs.reserve(10);

This is equivalent to calling the constuctor of vector<int> or vector<int>() for each element. Which means you'll have a zero-sized vectors. But remember, you can't use them unless you resize (not reserve) your vectors.

Remember, too, that it could be sometimes more efficient to resize with the initial size that you would need. So it's useful to do something like

vector<vector<int> > vecs(3,vector<int>(5));

This will create a vector with size 3, and each element will contain a vector of size 5.

Remember also, that it could be more efficient to use deque rather than vector if you're going to resize your vectors often. They're easy to use (as vectors) and you don't need to reserve, since the elements are not contiguous in memory.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!