When will the capacity of the vector decrease?

(This question is not about shrink_to_fit tricks (using swap() or shrink_to_fit() in C ++ 11).)

If I use the vector only through insert() , erase() , push_back() , pop_back() , clear() , when the capacity is insufficient, it will increase and redistribution for the vector will occur. But under what circumstances will productivity decrease? And will capacity reduction necessarily cause redistribution?

+4
source share
4 answers

The standard guarantees that no links / iterators will be invalidated during, for example, pop_back . From [container.requirements.general]:

Unless otherwise specified (explicitly or by defining a function in terms of other functions), referring to a member function of a container or passing a container as an argument, library functions should not invalidate iterators or change the values โ€‹โ€‹of objects in this container.

And there is no other specification, for example. pop_back

Thus, this means that redistribution cannot occur. 1


<Sub> 1. In the comments to another answer, it was suggested that, possibly, the memory corresponding to the pop-up element can be freed, which will not lead to the cancellation of references to "live" elements.

But then this will prevent re-growth of the array, as the standard states that inserts cannot cause redistribution until the size exceeds capacity. From [vector.capacity]:

It is guaranteed that redistribution does not occur during insertions that occur after the call to reserve() until the insertion makes the vector size larger than the value of capacity() .

sub>

+9
source

No, pop_back() does not. Others, of course, do not. The only way is as you mentioned.

 template< typename T, class Allocator > void shrink_capacity(std::vector<T,Allocator>& v) { std::vector<T,Allocator>(v.begin(),v.end()).swap(v); } 

And shrink_to_fit() in C ++ 11

+5
source

can be reduced if utilization is less than 1/4 of the capacity (this will lead to amortization of the fixed cost of redistribution). But the implementation of STL is not required to reduce the vector at any time when you use only the methods you have listed.

0
source

The C ++ standard does not require std::vector to reduce capacity() at any given time during its existence. It is strictly implementation dependent. Thus, an implementation may be on its own, but you should not rely on this behavior.

0
source

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


All Articles