473,387 Members | 1,504 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,387 software developers and data experts.

Conditional erasing elements from list - in a loop

Over one year ago somebody asked here: how to
remove selected elements from list
in a loop?. The answer was as follows:
for( it = l.begin(); it != l.end; ) {
if(...)
it = l.erase(it);
else
++it;
}
I use STL list, and I do the same like this:
for( it = l.begin(); it != l.end; ++it ) {
if(...) l.erase(it--);
}
Is that OK? Or does it depend on details
of the list implementation ??
Has it to be guaranteed that the operator --
is called before invalidation of the itarator?

regards -
O.C.
Jul 23 '05 #1
12 2287
"Tescobar" <ol**************@gmail.com> wrote in message
news:7a******************************@localhost.ta lkaboutprogramming.com...
Over one year ago somebody asked here: how to
remove selected elements from list
in a loop?. The answer was as follows:
for( it = l.begin(); it != l.end; ) {
if(...)
it = l.erase(it);
else
++it;
}
I use STL list, and I do the same like this:
for( it = l.begin(); it != l.end; ++it ) {
if(...) l.erase(it--);
}
Is that OK? Or does it depend on details
of the list implementation ??
Has it to be guaranteed that the operator --
is called before invalidation of the itarator?

'operator --' must be called before 'erase' is called, because the
result of 'operator --' is passed to 'erase'. So I do not see why this
would not be ok. Though the first version is clearer and at least as
fast as the second version.

regards
--
jb

(reply address in rot13, unscramble first)
Jul 23 '05 #2
Tescobar wrote:
[..]
for( it = l.begin(); it != l.end; ++it ) {
I hope you meant

for( it = l.begin(); it != l.end(); ++it ) {
if(...) l.erase(it--);
}
Is that OK? [...]


No. If the first element is to be erased, you will make 'it' invalid
by decrementing it past the 'l.begin()'. Incrementing it again does
not necessarily bring it back to be valid -- undefined behaviour.

V
Jul 23 '05 #3
On 2005-07-21 13:01:04 -0400, "Tescobar" <ol**************@gmail.com> said:
Over one year ago somebody asked here: how to
remove selected elements from list
in a loop?. The answer was as follows:
for( it = l.begin(); it != l.end; ) {
if(...)
it = l.erase(it);
else
++it;
}
I use STL list, and I do the same like this:
for( it = l.begin(); it != l.end; ++it ) {
if(...) l.erase(it--);
}
Is that OK? Or does it depend on details
of the list implementation ??
Has it to be guaranteed that the operator --
is called before invalidation of the itarator?


Think about what happens when the very first item in the list is being
erased (you'll run off the beginning of the list). Additionally, if you
can make the condition of your if() into a predicate, then you could
reduce the whole thing down to:

l.remove_if(predicate);

--
Clark S. Cox, III
cl*******@gmail.com

Jul 23 '05 #4
Clark S. Cox III wrote:
On 2005-07-21 13:01:04 -0400, "Tescobar" <ol**************@gmail.com> said:
Over one year ago somebody asked here: how to
remove selected elements from list
in a loop?. The answer was as follows:
for( it = l.begin(); it != l.end; ) {
if(...)
it = l.erase(it);
else
++it;
}
I use STL list, and I do the same like this:
for( it = l.begin(); it != l.end; ++it ) {
if(...) l.erase(it--);
}
Is that OK? Or does it depend on details
of the list implementation ??
Has it to be guaranteed that the operator --
is called before invalidation of the itarator?

Think about what happens when the very first item in the list is being
erased (you'll run off the beginning of the list). Additionally, if you
can make the condition of your if() into a predicate, then you could
reduce the whole thing down to:

l.remove_if(predicate);


Don't you mean

l.erase(l.remove_if(predicate));

??

V
Jul 23 '05 #5
"Victor Bazarov" <v.********@comAcast.net> wrote in message
news:%I*******************@newsread1.mlpsca01.us.t o.verio.net...
Clark S. Cox III wrote:
l.remove_if(predicate);

Don't you mean

l.erase(l.remove_if(predicate));

??


remove_if returns void and already takes care of erasing.

regards
--
jb

(reply address in rot13, unscramble first)
Jul 23 '05 #6
Jakob Bieling wrote:
"Victor Bazarov" <v.********@comAcast.net> wrote in message
news:%I*******************@newsread1.mlpsca01.us.t o.verio.net...

Clark S. Cox III wrote:


l.remove_if(predicate);


Don't you mean

l.erase(l.remove_if(predicate));

??

remove_if returns void and already takes care of erasing.


I must confuse it with std::remove_if ...

V
Jul 23 '05 #7
On 2005-07-21 14:21:39 -0400, Victor Bazarov <v.********@comAcast.net> said:
Clark S. Cox III wrote:
On 2005-07-21 13:01:04 -0400, "Tescobar" <ol**************@gmail.com> said:
for( it = l.begin(); it != l.end; ++it ) {
if(...) l.erase(it--);
}
Is that OK? Or does it depend on details
of the list implementation ??
Has it to be guaranteed that the operator --
is called before invalidation of the itarator?

Think about what happens when the very first item in the list is being
erased (you'll run off the beginning of the list). Additionally, if you
can make the condition of your if() into a predicate, then you could
reduce the whole thing down to:

l.remove_if(predicate);


Don't you mean

l.erase(l.remove_if(predicate));


Nope, I mean just what I said.

--
Clark S. Cox, III
cl*******@gmail.com

Jul 23 '05 #8
"Tescobar" <ol**************@gmail.com> wrote in message
news:7a******************************@localhost.ta lkaboutprogramming.com...
I use STL list, and I do the same like this:
for( it = l.begin(); it != l.end; ++it ) {
if(...) l.erase(it--);
}
Is that OK? Or does it depend on details
of the list implementation ??


It is not OK, because if it == l.begin(), then it-- causes undefined
behavior.
Jul 23 '05 #9

Tescobar wrote:
Over one year ago somebody asked here: how to
remove selected elements from list
in a loop?. The answer was as follows:
for( it = l.begin(); it != l.end; ) {
if(...)
it = l.erase(it);
else
++it;
}
I use STL list, and I do the same like this:
for( it = l.begin(); it != l.end; ++it ) {
if(...) l.erase(it--);
}
Is that OK? Or does it depend on details
of the list implementation ??
Has it to be guaranteed that the operator --
is called before invalidation of the itarator?


The post decrement operator will be applied before the call to erase,
but as others have pointed out there is an out-of-range problem with
the iterator. A slight change does correct this problem
for( it = l.begin(); it != l.end(); ++it ) {
if(...) it = l.erase(it);
}
But the code is still messier than it need be. Abstracting the loop
operation and hiding the specifics of its implementation, leads to more
compact and more likely correct code in many cases.

Assuming that a predicate (or a value) can serve as the test for
deletion, I would recommend this idiom for iterating and deleting items
from a container:
it.erase( std::remove_if( it.begin(), it.end(), ...), it.end());
Just insert the predicate or the value to be deleted in place of the
ellipsis.

Greg

Jul 23 '05 #10
"Greg" <gr****@pacbell.net> wrote in message
news:11*********************@g47g2000cwa.googlegro ups.com...
The post decrement operator will be applied before the call to erase,
but as others have pointed out there is an out-of-range problem with
the iterator. A slight change does correct this problem for( it = l.begin(); it != l.end(); ++it ) {
if(...) it = l.erase(it);
}


No it doesn't. Well, it does, but it introduces another problem, which
amounts to the same thing.

In this version, after you execute

it = l.erase(it);

you still increment "it". The result is that the code will skip the element
after each one erased.
Jul 23 '05 #11
my question was:
for( it = l.begin(); it != l.end(); ++it )
{
if(...) l.erase(it--);
}
Is that OK? [...]

Victor wrote:
No. If the first element is to be erased, you
will make 'it' invalid
by decrementing it past the 'l.begin()'.
Incrementing it again does
not necessarily bring it back to be valid -
undefined behaviour.


Are you sure, that this behaviour is undefined
by ANSI c++ ?
I use GNU compilers, where STL is implemented
by SGI. Here, as a matter of fact, list is
implemented as the circular structure, i.e.:

list<T> mylist;
list<T>::iterator p=mylist.end();
p++; assert(p==mylist.end());
p--; assert(p==mylist.end());
//now insert exactly one element:
mylist.push_front(something_of_type_T);
p=mylist.begin();
p--; assert(p==mylist.end());
p++; assert(p==mylist.begin());

is a valid code - none of the asserts fail.
In another words, one can traverse the same
list infinitely many times by repetitive
++ only (or -- only). During this, the
interator will be invalid only one time
each cycle - when passing its end() value.
I always thought, that such a behaviour
of list::iterator is implementation-independend.
Has anybody seen a counterexample, i.e. an
implementation which is still ANSI c++ compliant,
by does not obey "circularity" ?

Best regards from Poland :-)
O.C.

Jul 24 '05 #12


Tescobar wrote:
Over one year ago somebody asked here: how to
remove selected elements from list
in a loop?. The answer was as follows:
for( it = l.begin(); it != l.end; ) {
if(...)
it = l.erase(it);
else
++it;
}

I think more universal would be:
for( it = l.begin(); it != l.end; ) {
if(...)
l.erase(it++);
else
++it;
}

This should work with any STL container. Original would not work for
map and set for example.

Regards,
Vyacheslav

Jul 25 '05 #13

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

Similar topics

8
by: Generic Usenet Account | last post by:
To settle the dispute regarding what happens when an "erase" method is invoked on an STL container (i.e. whether the element is merely removed from the container or whether it also gets deleted in...
11
by: eeykay | last post by:
Hello, I am facing a starnge problem while erasing the last member in a vector. I am using VC++ .NET 2002 complier. I have vector of CComPtr<..> (irrelevant here), and then I iterate over the...
5
by: ma740988 | last post by:
For starters, Happy New Year to all!! I created a vector of pairs where pair first is a primitive and pair second is a vector of ints. So now: # include <iostream> # include <vector>
8
by: Jim Langston | last post by:
There's the thing about iterating though a map or vector when you may delete one of the elements, where you simply assign the iterator to the map.erase() statement or increment it if you don't. ...
13
by: mahajan.vibhor | last post by:
I have a list of pointers. e.g A* a = new A(); // A is a class stl::list<A*list_a; I am inserting object of class in the after allocating memeory thru new operator. But when i want to...
56
by: Zytan | last post by:
Obviously you can't just use a simple for loop, since you may skip over elements. You could modify the loop counter each time an element is deleted. But, the loop ending condition must be...
3
by: Angus | last post by:
If I want to erase all list items with a value of say 3 as below: std::list<intmylist; mylist.push_back(3); mylist.push_back(4); mylist.push_back(5); mylist.push_back(6); ...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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...
0
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,...
0
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...

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.