Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all items from a c++ std::vector

Tags:

c++

stl

vector

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

like image 591
michael Avatar asked Oct 06 '09 13:10

michael


People also ask

How do I delete everything from a vector in C++?

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.

How do you clear a std::vector?

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 .

How do I remove multiple elements from a vector in C++?

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.

How do you delete all elements in a 2d vector?

To remove all the vectors from the 2-D vector, 'clear()' function can be used.


2 Answers

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();  
like image 64
Khaled Alshaya Avatar answered Sep 21 '22 23:09

Khaled Alshaya


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); 
like image 41
aJ. Avatar answered Sep 23 '22 23:09

aJ.