473,386 Members | 1,702 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

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<iostream>
int main(){
list<string> 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");
// I want to erase entries that say "deleteme"

I can get and iterator, but that screws up things
list<string>::iterator 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 1928
* 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<iostream>
int main(){
list<string> 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");
// I want to erase entries that say "deleteme"

I can get and iterator, but that screws up things
list<string>::iterator 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::iterator 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_iterator<std::string>( 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.google.c om...
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(){
list<string> l;
std::list<std::string> l; /* I *hate* that identifier! :-) */
l.push_back("first");
l.push_back("second");
l.push_back("deleteme");
l.push_back("fourth");
l.push_back("deleteme");
l.push_back("sixth");
// I want to erase entries that say "deleteme"

I can get and iterator, but that screws up things
list<string>::iterator it=l.begin();
std::list<std::string>::iterator 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::erase() 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<iostream>
#include<list>
#include<string>

int main()
{
std::list<std::string> 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");

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

for(std::list<std::string>::iterator it = l.begin(); it!=l.end(); it++)
if((*it).compare("deleteme") == 0)
it = l.erase(it);

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

Also look up 'std::list::remove_if()'

-Mike
Jul 22 '05 #3
"Mike Wahler" <mk******@mkwahler.net> wrote in message
news:TR*****************@newsread1.news.pas.earthl ink.net...

for(std::list<std::string>::iterator it = l.begin(); it!=l.end(); it++) if((*it).compare("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.individual.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<iostream>
int main(){
list<string> 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");
// I want to erase entries that say "deleteme"

I can get and iterator, but that screws up things
list<string>::iterator 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::iterator 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_iterator<std::string>( 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<std::string>::iterator it = l.begin(); it!=l.end(); it++)
if((*it).compare("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******@mkwahler.net> wrote in message
news:TR*****************@newsread1.news.pas.earthl ink.net...

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

it++)
if((*it).compare("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.individual.net...
* Mike Wahler:
"Mike Wahler" <mk******@mkwahler.net> wrote in message
news:TR*****************@newsread1.news.pas.earthl ink.net...

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

it++)
if((*it).compare("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
"Mike Wahler" <mk******@mkwahler.net> wrote in message

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::erase() 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<iostream>
#include<list>
#include<string>

int main()
{
std::list<std::string> 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");

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

for(std::list<std::string>::iterator it = l.begin(); it!=l.end(); it++)
if((*it).compare("deleteme") == 0)
it = l.erase(it);

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

Also look up 'std::list::remove_if()'

-Mike


There is something strange about this which I don't understand:
Consider the output of the following program:
#include<string>
#include<iostream>
using namespace std;

int main(){
list<string> l;
l.push_back("first");
l.push_back("second");
l.push_back("deleteme");
l.push_back("deleteme");
l.push_back("deleteme");
l.push_back("third");
l.push_back("fourth");

l.push_back("fifth");
l.push_back("deleteme");
list<string>::iterator it;
for(it=l.begin(); it!=l.end(); it++)
cout << (*it) << endl;
cout << "=================\n";
for( it=l.begin(); it != l.end(); it++){
cout << "It points to:" << *it <<endl;
if ((*it).compare("deleteme")==0)
it=l.erase(it);

}
cout << "++++++++++++++++\n";
for(it=l.begin(); it!=l.end(); it++)
cout << (*it) << endl;

}
===================== OUTPUT
$ ./test_iterators.cc.exe
first
second
deleteme
deleteme
deleteme
third
fourth
fifth
deleteme
=================
It points to:first
It points to:second
It points to:deleteme
It points to:deleteme
It points to:fourth
It points to:fifth
It points to:deleteme
It points to:first
It points to:second
It points to:deleteme
It points to:fourth
It points to:fifth
++++++++++++++++
first
second
third
fourth
fifth
$
==============================
I have 2 questions:
1) why does iterator never pointed to the element "third"?
2) why is the list traversed twice? (and the element "third" is missed both times)
thanks
Jul 22 '05 #11
"Christoff Pale" <ch************@yahoo.com> wrote in message
news:73**************************@posting.google.c om...

There is something strange about this which I don't understand:
for( it=l.begin(); it != l.end(); it++){
cout << "It points to:" << *it <<endl;
if ((*it).compare("deleteme")==0)
it=l.erase(it);

}


See my followup post where I point out the error I made
in my example, and see Alf's post for something that actually
works correctly.
-Mike
Jul 22 '05 #12
On Thursday 02 September 2004 09:35 am, Christoff Pale did deign to grace us
with the following:
"Mike Wahler" <mk******@mkwahler.net> wrote in message

When you delete an element to which the iterator points,
that iterator becomes invalidated. Then you try to increment
that invalid iterator. Undefined behavior.
There is something strange about this which I don't understand:
Consider the output of the following program:

.... $
==============================
I have 2 questions:
1) why does iterator never pointed to the element "third"?
You're doing the cout before the delete. At that time, 'it' points
at the first "deleteme." 'it' gets assigned the next value, which in
this case happens to be the second "deleteme", which it dutifully
shows you next pass. It's still there because the iterator has
already been assigned to the following one and incremented.
2) why is the list traversed twice? (and the element "third" is missed
both times) thanks


Presumably, the computer remembers that when it went through the
first time, it left a "deleteme" behind. In this pass, you see
"deleteme" again, but when this one is deleted _and 'it' assigned
to point to "third"_, you don't see "third", because 'it' gets incremented
at the top of the loop.

Try it with a cout on either side of the delete, and see what happens. :-)

Cheers!
Rich

Jul 22 '05 #13

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

Similar topics

3
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...
5
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...
18
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 ...
16
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........'...
2
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...
7
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...
5
by: Manish | last post by:
The topic is related to MySQL database. Suppose a table "address" contains the following records ------------------------------------------------------- | name | address | phone |...
10
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...
2
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
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...

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.