Solved

deleting objects from a vector...

Posted on 2008-06-11
4
377 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

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The viewer will learn how to use NetBeans IDE 8.0 for Windows to connect to a MySQL database. Open Services Panel: Create a new connection using New Connection Wizard: Create a test database called eetutorial: Create a new test tabel called ee…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

760 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

22 Experts available now in Live!

Get 1:1 Help Now