I'm trying to delete everything from a std::vector
by using the following code
vector.erase( vector.begin(), vector.end() );
but it doesn't work.
Update: Doesn't clear destruct the elements held by the vector? I don't want that, as I'm still using the objects, I just want to empty the container
clear() removes all the elements from a vector container, thus making its size 0. All the elements of the vector are removed using clear() function.
vec. clear() clears all elements from the vector, leaving you with a guarantee of vec. size() == 0 . vec = std::vector<int>() calls the copy/move(Since C++11) assignment operator , this replaces the contents of vec with that of other .
If you need to remove multiple elements from the vector, the std::remove will copy each, not removed element only once to its final location, while the vector::erase approach would move all of the elements from the position to the end multiple times.
To remove all the vectors from the 2-D vector, 'clear()' function can be used.
I think you should use std::vector::clear
:
vec.clear();
EDIT:
Doesn't clear destruct the elements held by the vector?
Yes it does. It calls the destructor of every element in the vector before returning the memory. That depends on what "elements" you are storing in the vector. In the following example, I am storing the objects them selves inside the vector:
class myclass { public: ~myclass() { } ... }; std::vector<myclass> myvector; ... myvector.clear(); // calling clear will do the following: // 1) invoke the deconstrutor for every myclass // 2) size == 0 (the vector contained the actual objects).
If you want to share objects between different containers for example, you could store pointers to them. In this case, when clear
is called, only pointers memory is released, the actual objects are not touched:
std::vector<myclass*> myvector; ... myvector.clear(); // calling clear will do: // 1) --------------- // 2) size == 0 (the vector contained "pointers" not the actual objects).
For the question in the comment, I think getVector()
is defined like this:
std::vector<myclass> getVector();
Maybe you want to return a reference:
// vector.getVector().clear() clears m_vector in this case std::vector<myclass>& getVector();
vector.clear()
should work for you. In case you want to shrink the capacity of the vector
along with clear then
std::vector<T>(v).swap(v);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With