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?
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.
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.
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.
The pop_back is void function, it is nonvalue-returning.
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()
.
No. pop_back() will not shrink the capacity of vector. use
std::vector<T>(v).swap(v)
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With