Solved

deleting objects from a vector...

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

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

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

Suggested Solutions

Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
The viewer will learn how to synchronize PHP projects with a remote server in NetBeans IDE 8.0 for Windows.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

828 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