使std :: vector capacity> = N和si​​ze = 0的最佳方法是什么?

los*_*los 6 c++ vector std stdvector

鉴于a std::vector,其大小和容量可以是任意的,将其大小更改为0并将容量更改为至少N(给定数量)的最佳做法是什么?

我的直接想法是:

void f(vector<int> &t, int N)
{
    t.clear();
    t.reserve(N);
}
Run Code Online (Sandbox Code Playgroud)

但我注意到了

不能保证重新分配,并且不保证向量容量会改变(当调用std :: vector :: clear时).

所以我想知道当原始容量大于给定的N时,如何避免重新分配?

eer*_*ika 4

what's the best practice to change its size to 0 and capacity to N(a given number)? My direct idea is: ...

Your direct idea is correct, and the simplest option. Although to be pedantic, reserve changes capacity to greater or equal to the given number; not guaranteed to be equal (but all implementations I've tested do allocate exactly the given amount if the previous capacity was less).

So I'm wondering how to avoid reallocating when the origin capacity is larger than the given N?

By using a standard library implementation that has chosen to not deallocate the memory on a call to clear (i.e. any standard conforming implementation, as indicated by the answer here).


Another approach to guarantee (although, it appears that this is not necessary as the above should be guaranteed, despite the weak wording on cplusplus.com) no reallocation (in the case N > t.capacity()): Since the vector contains simple integers, and you appear to know how many elements there will be (as you know to reserve), you could simply call t.resize(N) (to remove extra elements in case size was greater) without clearing the vector, and then proceed to overwrite the existing elements, rather than push new ones.

Of course, this means that you won't be able to observe the number of elements that have been overwritten, so this approach is not applicable for all use cases. It's fine if you simply want to fill the vector with a simple loop.

如果新大小可能大于旧大小,并且您不希望过度分配,您可能需要在调整大小之前进行保留。这是因为大多数实现在保留上分配精确的数量(正如我提到的),但在调整大小时使用乘法策略(据我所知,这些行为都不能得到保证,但我使用的实现与此行为一致)。