Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reduce the capacity of an stl vector

Tags:

c++

stl

vector

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.

like image 601
ynimous Avatar asked Jul 10 '09 18:07

ynimous


People also ask

How do you reduce vector capacity?

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();

How do you set the capacity of a vector?

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.

Does vector clear reduce capacity?

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.

Does Pop_back reduce size?

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.


2 Answers

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.

like image 83
aJ. Avatar answered Sep 28 '22 17:09

aJ.


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 reduce capacity() to size(). [Note: The request is non-binding to allow latitude for implementation-specific optimizations. —end note]

like image 37
Michael Kristofik Avatar answered Sep 28 '22 15:09

Michael Kristofik