473,695 Members | 2,389 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

deleting list objects

I would like to know if my method to remove list objects is correct in
this small test program. It seems to me that there might be a simplier
way, but I'm afraid I don't know enough about list iterators and how
they are behaving in situations like this.

#include <iostream>
#include <list>

class Test;
typedef std::list< Test* > Tlist;
Tlist objects;

class Test
{
private:
bool Active;
int xx;
public:
Test(bool a, int x)
: Active(a), xx(x) {}
void print() { std::cout << Active << " \t" << xx << std::endl; }
bool is_active() { return Active; }
};

void print_all (const char *msg)
{
std::cout << msg << std::endl;
for (Tlist::iterato r i = objects.begin() ; i != objects.end(); ++i)
(*i)->print();
}
void remove_active_o bjects()
{
for (Tlist::iterato r i = objects.begin() ; i != objects.end(); )
{
if ((*i)->is_active())
{
Tlist::iterator temp = i;
++i;
objects.erase(t emp);
delete *temp;
}
else
{
++i;
}
}
}

int main()
{
objects.push_ba ck (new Test(true, 12));
objects.push_ba ck (new Test(false, 345));
objects.push_ba ck (new Test(false, 6789));
objects.push_ba ck (new Test(true, 19283));

print_all ("Before:");
remove_active_o bjects();
print_all ("After:");

for (Tlist::iterato r i = objects.begin() ; i != objects.end(); ++i)
delete *i;

return 0;
}

---------------------------------
Output of this program should be:

Before:
1 12
0 345
0 6789
1 19283
After:
0 345
0 6789

Jul 19 '05 #1
2 8242

"dasod" <No****@mapSoN. invalid> wrote in message
news:be******** **@news1.songne t.fi...
I would like to know if my method to remove list objects is correct in
this small test program. It seems to me that there might be a simplier
way, but I'm afraid I don't know enough about list iterators and how
they are behaving in situations like this.

#include <iostream>
#include <list>

class Test;
typedef std::list< Test* > Tlist;
Tlist objects;

class Test
{
private:
bool Active;
int xx;
public:
Test(bool a, int x)
: Active(a), xx(x) {}
void print() { std::cout << Active << " \t" << xx << std::endl; }
bool is_active() { return Active; }
};

void print_all (const char *msg)
{
std::cout << msg << std::endl;
for (Tlist::iterato r i = objects.begin() ; i != objects.end(); ++i)
(*i)->print();
}
void remove_active_o bjects()
{
for (Tlist::iterato r i = objects.begin() ; i != objects.end(); )
{
if ((*i)->is_active())
{
Tlist::iterator temp = i;
++i;
objects.erase(t emp);
delete *temp;


This is not correct, the iterator temp (which is just a copy of i) is no
longer valid after you've erased the item.

if ((*i)->is_active())
{
delete *i;
i = objects.erase(i );
}
else
{
++i;
}

john
Jul 19 '05 #2

"John Harrison" <jo************ *@hotmail.com> kirjoitti
viestissä:be*** *********@ID-196037.news.dfn cis.de...

"dasod" <No****@mapSoN. invalid> wrote in message
news:be******** **@news1.songne t.fi...
if ((*i)->is_active())
{
Tlist::iterator temp = i;
++i;
objects.erase(t emp);
delete *temp;
This is not correct, the iterator temp (which is just a copy of i) is

no longer valid after you've erased the item.

if ((*i)->is_active())
{
delete *i;
i = objects.erase(i );
}
else
{
++i;
}


Yes, it looks better now. Thanks a lot.
Jul 19 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
2034
by: Thomas Philips | last post by:
I have a question about deleting objects. My game has two classes, Player and Alien, essentially identical, instances of which can shoot at each other. Player is described below class Player(object): #Class attributes for class Player n=0 #n is the number of players #Private methods for class Player def __init__(self,name):
5
2732
by: flupke | last post by:
Hi, i'm having trouble with deleting elements from a list in a for loop ============== test program ============== el = print "**** Start ****" print "List = %s " % el index = 0 for line in el:
181
8797
by: Tom Anderson | last post by:
Comrades, During our current discussion of the fate of functional constructs in python, someone brought up Guido's bull on the matter: http://www.artima.com/weblogs/viewpost.jsp?thread=98196 He says he's going to dispose of map, filter, reduce and lambda. He's going to give us product, any and all, though, which is nice of him.
9
1882
by: Aguilar, James | last post by:
Hey guys. A new question: I want to use an STL libarary to hold a bunch of objects I create. Actually, it will hold references to the objects, but that's beside the point, for the most part. Here's the question: I want to be able to change the references (including deleting them). Is there any way to do that besides using pointers rather than references for the STL library? I'd also prefer to avoid using const_cast, if it is indeed...
12
1952
by: Christoff Pale | last post by:
Hi, suppose I have a list of strings; I have to iterate of the strings and delete certain entries. I and not sure how to do this? for example: #include<list> #include<string> #include<iostream> int main(){
2
1772
by: KraftDiner | last post by:
I have a list, and within it, objects are marked for deletion. However when I iterate through the list to remove objects not all the marked objects are deleted.. here is a code portion: i = 0 for obj in self.objList: if obj.mouseHit: print 'delete + ' + `i` self.objList.pop(i)
14
1640
by: Mark | last post by:
I'm making a game. I need to maintain a bunch of objects, in this case animations (explosions and stuff). I've decided to use an STL vector. From my understanding, I need to declare it as vector<Animation*so that I can insert new animations with something like myAnimations.push_back(new Animation(...)); So that's all fine and dandy, but what I can't decide on is how to delete this animation after it's done playing (the explosion should...
3
3722
by: Andy | last post by:
Hello, I have the following situation: Thread A is allocating a dataset, doing some low-level calculations and storing a pointer to the dataset in a std::list via push_back. Thread B should retrieve the pointer to the first dataset in the list, remove it from the list, and do some high level analysis. The problem now is, how do I efficiently retrieve the pointer?
2
1922
Parul Bagadia
by: Parul Bagadia | last post by:
I have written a code for deleting certain value from linklist; it's not working; where as i have written one for deleting a no., after given no. which works fine! I even debugged it; but invain; down here am posting my code; please somebody who can point it out; let me know fast; whats wrong in it... //Delete a number next to the given number void afterdelete() { struct linklist*temp=NULL; int no=0;
0
8631
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8572
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9115
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8984
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8825
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7661
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5839
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4579
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3003
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.