deleting objects from a vector...

I have a vector of pointers. I want to delete the objects the vectors point to. How is this done?
mattososkyAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
Infinity08Connect With a Mentor Commented:
You can iterate over the vector, and delete all objects. Something like :
std::vector<Object*> vec;
std::vector<Object*>::iterator it;
for (it = vec.begin(); it != vec.end(); ++it) {
  delete *it;
}

Open in new window

0
 
Infinity08Commented:
Oh, and to keep it clean, you probably want to either erase the delete pointers from the vector, or set them to NULL once they are deleted.
0
 
mattososkyAuthor Commented:
I did notice that you cant erase in iterator and keep iterating through the collection,, kind of lame but a vector.clear at the end does the trick.

Thanks
0
 
Infinity08Commented:
>> I did notice that you cant erase in iterator and keep iterating through the collection

Yes. But if you think about it, that's quite normal ... an iterator is an index over the data - if data elements are removed or added, then the index is no longer valid.

You can solve that by either always taking the last or first element of the vector. Note that the former (last element) is recommended, since it's more optimal.
0
All Courses

From novice to tech pro — start learning today.