Is there a way to reduce the capacity of a vector ?
My code inserts values into a vector (not knowing their number beforehand), and when this finishes, the vectors are used only for read operations.
I guess I could create a new vector, do a .reseve() with the size and copy the items, but I don't really like the extra copy operation.
PS: I don't care for a portable solution, as long as it works for gcc.
C++ std::vector Reducing the Capacity of a Vector In C++11 we can use the shrink_to_fit() member function for a similar effect: v. shrink_to_fit();
The theoretical limit on the size of a vector is given by member max_size. The capacity of a vector can be explicitly altered by calling member vector::reserve.
Starting with C++11, we can call the vector::shrink_to_fit function after clear() , which reduces the vector's capacity to fir the size. It works by “requesting” a reallocation on the vector.
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.
std::vector<T>(v).swap(v);
Swapping the contents with another vector swaps the capacity.
std::vector<T>(v).swap(v); ==> is equivalent to std::vector<T> tmp(v); // copy elements into a temporary vector v.swap(tmp); // swap internal vector data
Swap() would only change the internal data structure.
With C++11, you can call the member function shrink_to_fit()
. The draft standard section 23.2.6.2 says:
shrink_to_fit
is a non-binding request to reducecapacity()
tosize()
. [Note: The request is non-binding to allow latitude for implementation-specific optimizations. —end note]
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