Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does std::vector.pop_back() change vector's capacity?

If I allocated an std::vector to a certain size and capacity using resize() and reserve() at the beginning of my program, is it possible that pop_back() may "break" the reserved capacity and cause reallocations?

like image 264
jackhab Avatar asked Oct 08 '09 09:10

jackhab


People also ask

Does std::vector resize change capacity?

The C++ function std::vector::resize() changes the size of vector. If n is smaller than current size then extra elements are destroyed. If n is greater than current container size then new elements are inserted at the end of vector.

What does vector Pop_back do?

vector::pop_back()() pop_back() function is used to pop or remove elements from a vector from the back. The value is removed from the vector from the end, and the container size is decreased by 1.

Does Pop_back free memory?

pop_back() will call the destructor of whatever's contained in the vector. In this case, it calls the destructor of a pointer -- which does absolutely nothing! You need to explicitly destroy the objects pointed at by the elements of your vector, as you did in your first code sample.

Does vector Pop_back return value?

The pop_back is void function, it is nonvalue-returning.


2 Answers

No. The only way to shrink a vector's capacity is the swap trick

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

and even that isn't guaranteed to work according to the standard. (Although it's hard to imagine an implementation where it wouldn't work.)

As far as I know, the next version of the C++ standard (what used to be C++0x, but now became C++1x) will have std::vector<>::shrink_to_fit().

like image 131
sbi Avatar answered Oct 30 '22 13:10

sbi


No. pop_back() will not shrink the capacity of vector. use std::vector<T>(v).swap(v) instead.

like image 45
aJ. Avatar answered Oct 30 '22 12:10

aJ.