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.
I'm not saying that GCC couldn't have some method for doing what you want without a copy, but it would be tricky to implement (I think) because vectors need to use an
Allocator
object to allocate and deallocate memory, and the interface for anAllocator
doesn't include areallocate()
method. I don't think it would be impossible to do, but it might be tricky.The idiomatic solution is to swap with a newly constructed vector.
Edit: I misread the question. The code above will clear the vector. OP wants to keep the elements untouched, only shrink
capacity()
tosize()
.It is difficult to say if aJ's code will do that. I doubt there's portable solution. For
gcc
, you'll have to take a look at their particular implementation ofvector
.edit: So I've peeked at libstdc++ implementation. It seems that aJ's solution will indeed work.
See the source, line 232.
With C++11, you can call the member function
shrink_to_fit()
. The draft standard section 23.2.6.2 says:Get the "Effective STL" book by Scott Myers. It has a complete item jus on reducing vector's capacity.
Swapping the contents with another vector swaps the capacity.
Swap() would only change the internal data structure.
Old thread, I know, but in case anyone is viewing this in the future.. there's shrink_to_fit() in C++11 but since it is a non-binding request, the behaviour will depend on its implementation.
See: http://en.cppreference.com/w/cpp/container/vector/shrink_to_fit