473,748 Members | 4,065 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

deleting entries in a list

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<iostre am>
int main(){
list<string> l;
l.push_back("fi rst");
l.push_back("se cond");
l.push_back("de leteme");
l.push_back("fo urth");
l.push_back("de leteme");
l.push_back("si xth");
// I want to erase entries that say "deleteme"

I can get and iterator, but that screws up things
list<string>::i terator it=l.begin();
for( ; it!=l.end(); it++){
if( (*it).compare(" deleteme")==0){
l.erase(it);
}
}
}

This gives me segmentation fault

I think that when I delete the first "deleteme" the
it now points to "fourth";

Basically, this is what I want.
I will have a huge list of some object.
I want to traverse it all the way and delete
objects that meet a certain criteria.
any help will be much appreciated.
thanks
Jul 22 '05 #1
12 1959
* Christoff Pale:

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<iostre am>
int main(){
list<string> l;
l.push_back("fi rst");
l.push_back("se cond");
l.push_back("de leteme");
l.push_back("fo urth");
l.push_back("de leteme");
l.push_back("si xth");
// I want to erase entries that say "deleteme"

I can get and iterator, but that screws up things
list<string>::i terator it=l.begin();
for( ; it!=l.end(); it++){
if( (*it).compare(" deleteme")==0){
l.erase(it);
}
}
}

This gives me segmentation fault

#include <algorithm>
#include <iostream>
#include <list>
#include <string>

int main()
{
typedef std::list<std:: string> StringList;
typedef StringList::ite rator Iterator;

StringList l;
l.push_back( "first" );
l.push_back( "second" );
l.push_back( "deleteme" );
l.push_back( "fourth" );
l.push_back( "deleteme" );
l.push_back( "sixth" );

for( Iterator it = l.begin(); it != l.end(); )
{
it->compare( "deleteme" ) == 0? it = l.erase( it ) : ++it;
}

std::copy(
l.begin(), l.end(),
std::ostream_it erator<std::str ing>( std::cout, "\n" )
);
}

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 22 '05 #2

"Christoff Pale" <ch************ @yahoo.com> wrote in message
news:73******** *************** ***@posting.goo gle.com...
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<iostre am>
int main(){
list<string> l;
std::list<std:: string> l; /* I *hate* that identifier! :-) */
l.push_back("fi rst");
l.push_back("se cond");
l.push_back("de leteme");
l.push_back("fo urth");
l.push_back("de leteme");
l.push_back("si xth");
// I want to erase entries that say "deleteme"

I can get and iterator, but that screws up things
list<string>::i terator it=l.begin();
std::list<std:: string>::iterat or it = l.begin();
for( ; it!=l.end(); it++){
if( (*it).compare(" deleteme")==0){
l.erase(it);
}
}
}

This gives me segmentation fault
When you delete an element to which the iterator points,
that iterator becomes invalidated. Then you try to increment
that invalid iterator. Undefined behavior.

I think that when I delete the first "deleteme" the
it now points to "fourth";
No it points to the outer moon of sixth planet circling
Alpha Seti. But that's just today. Tomorrow it would
point somewhere else.

std::list::eras e() returns an iterator that designates
the first element remaining beyond any elements removed,
or end() if no such element exists. So when you erase,
don't increment 'it', assign it the return value from
'erase()'.

Basically, this is what I want.
I will have a huge list of some object.
I want to traverse it all the way and delete
objects that meet a certain criteria.
any help will be much appreciated.


#include<iostre am>
#include<list>
#include<string >

int main()
{
std::list<std:: string> l;
l.push_back("fi rst");
l.push_back("se cond");
l.push_back("de leteme");
l.push_back("fo urth");
l.push_back("de leteme");
l.push_back("si xth");

std::cout << l.size() << '\n'; // prints 6

for(std::list<s td::string>::it erator it = l.begin(); it!=l.end(); it++)
if((*it).compar e("deleteme") == 0)
it = l.erase(it);

std::cout << l.size() << '\n'; // prints 4
return 0;
}

Also look up 'std::list::rem ove_if()'

-Mike
Jul 22 '05 #3
"Mike Wahler" <mk******@mkwah ler.net> wrote in message
news:TR******** *********@newsr ead1.news.pas.e arthlink.net...

for(std::list<s td::string>::it erator it = l.begin(); it!=l.end(); it++) if((*it).compar e("deleteme") == 0)
it = l.erase(it);


This isn't quite right. It produces a valid iterator,
but the 'for' loop increments it, which will skip
over the item after the erased one. See Alf's post
for a proper way to do this.

Sorry for the mistake.

-Mike
Jul 22 '05 #4
"Alf P. Steinbach" <al***@start.no > wrote in message
news:41******** ********@news.i ndividual.net.. .
* Christoff Pale:

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<iostre am>
int main(){
list<string> l;
l.push_back("fi rst");
l.push_back("se cond");
l.push_back("de leteme");
l.push_back("fo urth");
l.push_back("de leteme");
l.push_back("si xth");
// I want to erase entries that say "deleteme"

I can get and iterator, but that screws up things
list<string>::i terator it=l.begin();
for( ; it!=l.end(); it++){
if( (*it).compare(" deleteme")==0){
l.erase(it);
}
}
}

This gives me segmentation fault

#include <algorithm>
#include <iostream>
#include <list>
#include <string>

int main()
{
typedef std::list<std:: string> StringList;
typedef StringList::ite rator Iterator;

StringList l;
l.push_back( "first" );
l.push_back( "second" );
l.push_back( "deleteme" );
l.push_back( "fourth" );
l.push_back( "deleteme" );
l.push_back( "sixth" );

for( Iterator it = l.begin(); it != l.end(); )
{
it->compare( "deleteme" ) == 0? it = l.erase( it ) : ++it;
}

std::copy(
l.begin(), l.end(),
std::ostream_it erator<std::str ing>( std::cout, "\n" )
);
}


Whoah, that's giving me Perl flashbacks! Is there something wrong with
if/else? ;-)

--
David Hilsee
Jul 22 '05 #5
* Mike Wahler:

for(std::list<s td::string>::it erator it = l.begin(); it!=l.end(); it++)
if((*it).compar e("deleteme") == 0)
it = l.erase(it);


What happens here if there are two "deleteme" items in sequence, or
if there is a "deleteme" item at the end of the list?

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 22 '05 #6
* Mike Wahler:
"Mike Wahler" <mk******@mkwah ler.net> wrote in message
news:TR******** *********@newsr ead1.news.pas.e arthlink.net...

for(std::list<s td::string>::it erator it = l.begin(); it!=l.end();

it++)
if((*it).compar e("deleteme") == 0)
it = l.erase(it);


This isn't quite right. It produces a valid iterator,
but the 'for' loop increments it, which will skip
over the item after the erased one. See Alf's post
for a proper way to do this.


I'm sorry for already responding to your previous posting before
reading this. Grr. When shall I learn to read _everything_ first?

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 22 '05 #7

"Alf P. Steinbach" <al***@start.no > wrote in message
news:41******** ********@news.i ndividual.net.. .
* Mike Wahler:
"Mike Wahler" <mk******@mkwah ler.net> wrote in message
news:TR******** *********@newsr ead1.news.pas.e arthlink.net...

for(std::list<s td::string>::it erator it = l.begin(); it!=l.end();

it++)
if((*it).compar e("deleteme") == 0)
it = l.erase(it);


This isn't quite right. It produces a valid iterator,
but the 'for' loop increments it, which will skip
over the item after the erased one. See Alf's post
for a proper way to do this.


I'm sorry for already responding to your previous posting before
reading this. Grr. When shall I learn to read _everything_ first?


No problem. I sometimes do the same thing myself.

-Mike
Jul 22 '05 #8

"Alf P. Steinbach"
* Christoff Pale: [...] for( Iterator it = l.begin(); it != l.end(); )
{
it->compare( "deleteme" ) == 0? it = l.erase( it ) : ++it;
it->compare( "deleteme" ) == 0? it = l.erase( it/*!*/++/*!*/ ) : ++it;
}


Heinz
Jul 22 '05 #9
* Heinz Ozwirk:

"Alf P. Steinbach"
* Christoff Pale:

[...]
for( Iterator it =3D l.begin(); it !=3D l.end(); )
{
it->compare( "deleteme" ) =3D=3D 0? it =3D l.erase( it ) : =

++it;
=20
it->compare( "deleteme" ) =3D=3D 0? it =3D l.erase( it/*!*/++/*!*/ ) =
: ++it;
}


If (and here I'm guessing) that is supposed to mean
it = l.erase( it++ )
then that's wrong.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 22 '05 #10

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

Similar topics

3
1820
by: Patrick von Harsdorf | last post by:
I want to iterate over a collection and delete all unwanted entries. for item in collection: del item of course doesn´t do anything useful. Two things come to mind: a) iterating backwards over the collection using indexing, something like: for i in range(len(collection)-1, -1, -1): item = collection
5
2734
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:
18
2480
by: Dan | last post by:
hello, I would to know if it is possible to delete an instance in an array, The following does not allow me to do a delete. I am trying to find and delete the duplicate in an array, thanks for ( j =0; j<MAX ; j++) { for ( i =0; i<MAX ; i++)
16
2146
by: Josué Maldonado | last post by:
Hello list, The TCL trigger that uses NEW and OLD arrays failed after after I removed a unused column, now I got this error: pltcl: Cache lookup for attribute '........pg.dropped.24........' type 0 failed I already did a vacuum, but the error remain. Any idea how to fix/avoid that?
2
1867
by: Stuart Norris | last post by:
Dear Readers, I am developing an application that stores "messages" in array list and writes new entries to a disk file at the end. This file is used incase the user choses to restart the program. When the program is restarted the messages are replayed so the application knows where it is up to. I am not allowed to use a **database** I have been instructed to use a flat file. The application I am replacing does that.
7
1833
by: eSolTec, Inc. 501(c)(3) | last post by:
Thank you in advance for any and all assistance. I have an application that pulls files, folders and registry keys of installed programs. I'm wanting to with a context menu selection of "Delete Selected", delete "ALL" of the checked selected files, folders, registry keys. Can someone show me some code to do this please?
5
3990
by: Manish | last post by:
The topic is related to MySQL database. Suppose a table "address" contains the following records ------------------------------------------------------- | name | address | phone | ------------------------------------------------------- | mr x | 8th lane | 124364 | | mr x | 6th lane | 435783 | | mrs x | 6th lane | 435783 |
10
2778
by: Boltar | last post by:
Hello I need to iterate through an STL list container and delete certain entries in it. I realise if use erase() with the iterator it will invalidate it but what if I store it beforehand? Ie: is the code below using a 2nd iterator variable always guaranteed to work or could there be come internal implementation magic going on inside the list that could prevent it? for(iter=objlist.begin();iter != objlist.end();++iter)
2
1488
by: helraizer1 | last post by:
Hi folks, I have a file for my chatbox called data.line, which the posts are in the layout CHATBOXTEXT 7 username=helraizer 1202416953
0
8987
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...
1
9316
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9241
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
8239
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...
1
6793
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4867
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3303
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
2
2777
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2211
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.