Resetting std:vector?

This is a discussion on Resetting std:vector? within the C++ Programming forums, part of the General Programming Boards category; Hey, I'm having trouble emptying a std:vector<int>. It seems if I resize it to a given number I can not ...

Resetting std:vector?

Hey, I'm having trouble emptying a std:vector<int>. It seems if I resize it to a given number I can not perform any action on it so that vector.capacity() returns 0 again. Tried with vector.resize(0) and vector.clear() but vector.capacity() will still return the number from before the resize.

I need to reset the vector to 0 elements and free up all memory, how do I do that? The vector is used in a static class instance.

Basically it swaps with a newly constructed vector that presumably has much smaller capacity. The vector swap likely just swaps internal pointers rather than copying anything, so it is fast. That's why small capacity of the temporary becomes the small capacity of my_data, and my_data's big capacity gets switched to the temporary, which is immediately destroyed and frees the memory.

Note that you cannot guarantee that capacity() will ever return 0. The vector might well eagerly allocate a block of data upon construction. (Not exactly a smart implementation, but legal.) Or it might use a small buffer optimization. (May give problems with vector's exception guarantees.)

CornedBee - I'll try to stay away from using capacity then but do you also mean that if I do the swap trick or create a new vector and then append a lot of elements that capacity may not return the correct number of elements?

Capacity is not supposed to return the number of elements, capacity() returns the number of elements that can be held before the next resize operation must take place. You probably want size() instead. Programs should very rarely, infact almost never ever need to care about the capacity() of a vector.

There is no "correct" capacity. It is basically implementation defined and it refers to how many elements can be stored in memory that has already been allocated.

You can tell the vector to reserve memory for at least a certain number of elements, but you can't force it to release memory (in a standard way).

Note that size() refers to the number of elements actually stored. Don't confuse size() with capacity(). You always control the size(), but you can really only make suggestions and minimums for the capacity().

To set the size() to zero, use clear() like I did in the previous example.