-
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.
-
can u copy over the vector with a new vector?
-
The swap trick is often suggested as a solution. I don't think it's guaranteed to work on all platforms or all situations, but it's commonly recommended so I'd give it a try.
Code:
std::vector<int> my_data(50000);
my_data.clear(); // empty vector with high capacity
// swap trick:
my_data.swap(std::vector<int>());
// or
std::vector<int>().swap(my_data);
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.)
-
Ok the swap thing did work. Thanks!
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.
-
Right so I use size() instead. Thanks a lot for the info! Managed to kill a nasty bug because of this.