Search code examples
c++stlstdvector

How to reduce the capacity of a std::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.


Solution

  • 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.