Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 419
  • Last Modified:

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?
0
mattososky
Asked:
mattososky
  • 3
1 Solution
 
Infinity08Commented:
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

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now