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.
Go look at Scott Meyers Effective STL item 17.
Basically you can't directly reduce the storage size of a
std::vector
.resize()
andreseve()
will never reduce the actually memory footprint of a container. The "trick" is to create a new container of the right size, copy the data and swap that with the current container. If we would like to clear a container out this is simply:If we have to copy the data over then we need to do the copy:
What this does is creates a new vector with the data from the old one, doing the copy that would be required in any operation that has the effect you need. Then calling
swap()
will just swap the internal buffers between the objects. At the end of the line the temporary vector that was created is deleted, but it has the guts from the old vector and the old vector has the guts from the new copy that is the exact size we need.No, you cannot reduce the capacity of a vector without copying. However, you can control how much new allocation growth by checking capacity() and call reserve() every time you insert something. The default behavior for std::vector is to grow its capacity by a factor of 2 every time new capacity is needed. You can growth it by your own magic ratio:
If you're into a bit hacky techniques, you can always pass in your own allocator and do whatever you need to do to reclaim the unused capacity.
If you're worried about about the overhead of your vector then maybe you should be looking to using another type of data structure. You mentioned that once your code is done initializing the vector it becomes a read only process. I would suggest going with an open ended array that will allow the program to decide its capacity at compile time. Or perhaps a linked list would be more suitable to your needs.
Lemme know if I completely misunderstood what you were getting at.
-UBcse