Solved

deleting objects from a vector...

Posted on 2008-06-11
4
383 Views
Last Modified: 2013-12-14
I have a vector of pointers. I want to delete the objects the vectors point to. How is this done?
0
Comment
Question by:mattososky
  • 3
4 Comments
 
LVL 53

Accepted Solution

by:
Infinity08 earned 500 total points
ID: 21764732
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
 
LVL 53

Expert Comment

by:Infinity08
ID: 21764807
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
 

Author Closing Comment

by:mattososky
ID: 31466390
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
 
LVL 53

Expert Comment

by:Infinity08
ID: 21766950
>> 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

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
Jaspersoft Studio is a plugin for Eclipse that lets you create reports from a datasource.  In this article, we'll go over creating a report from a default template and setting up a datasource that connects to your database.
The viewer will learn how to use and create keystrokes in Netbeans IDE 8.0 for Windows.
The viewer will learn how to synchronize PHP projects with a remote server in NetBeans IDE 8.0 for Windows.

813 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now