473,770 Members | 3,912 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

stl::list modified erase

Hi,

I am using multiple stl::list s of different types.

Now I want to write a function

list<type>::ite rator s_erase(list<ty pel, list<type>::ite rator it)

that takes an iterator and deletes the element it is pointing add, and
returns the iterator pointing to the predecessor of the erased element.

like this:

return l.erase(it)--;

But I want this to work for any contained type. For clarification:
I have theses lists:

list<cShipShips ;
list<cProjectil eProjectiles;
list<cAsteroidA steroids;

And I want my function to work on all of these lists. Is that possible?

Regards
Philip
Mar 17 '08 #1
12 2310
On Mar 17, 4:52 pm, Philip Mueller <m...@alienenpe ror.DELETETHIS. de>
wrote:
Hi,

I am using multiple stl::list s of different types.

Now I want to write a function

list<type>::ite rator s_erase(list<ty pel, list<type>::ite rator it)

that takes an iterator and deletes the element it is pointing add, and
returns the iterator pointing to the predecessor of the erased element.

like this:

return l.erase(it)--;

But I want this to work for any contained type. For clarification:
I have theses lists:

list<cShipShips ;
list<cProjectil eProjectiles;
list<cAsteroidA steroids;

And I want my function to work on all of these lists. Is that possible?

Regards
Philip

There already exists a method that does that: std::list::eras e
It sounds to me that you are making a function that does not do
anything differently than the method that exists? Am I missing
something?

Mar 17 '08 #2
On Mar 17, 5:54 pm, Christopher <cp...@austin.r r.comwrote:
On Mar 17, 4:52 pm, Philip Mueller <m...@alienenpe ror.DELETETHIS. de>
wrote:
Hi,
I am using multiple stl::list s of different types.
Now I want to write a function
list<type>::ite rator s_erase(list<ty pel, list<type>::ite rator it)
that takes an iterator and deletes the element it is pointing add, and
returns the iterator pointing to the predecessor of the erased element.
like this:
return l.erase(it)--;
But I want this to work for any contained type. For clarification:
I have theses lists:
list<cShipShips ;
list<cProjectil eProjectiles;
list<cAsteroidA steroids;
And I want my function to work on all of these lists. Is that possible?
Regards
Philip

There already exists a method that does that: std::list::eras e
It sounds to me that you are making a function that does not do
anything differently than the method that exists? Am I missing
something?
Oh, I see the only difference is std::list::eras e return an iterator
pointing to the element after the erased and you want it to point to
the element before.

Well, I see no reason you could not decrement the returned iterator,
as long as you check for the it = list.begin() case
Why even make a function for that? If you have the list handy, than
you have its type and can make an iterator, and call erase on it.

Mar 17 '08 #3
Kai-Uwe Bux wrote:
Sure. Define a function template:
[...]
Thanks, that's just what I need. Unfortunately I have never worked with
templates in C and I just can't get the syntax for a call to that
function right. Could you give an example?
BTW: I think, such a function fills a much needed gap in your code base.
Yeah, it would really make the project look a whole lot cleaner :-)

Regards
Philip
Mar 18 '08 #4
Philip Mueller wrote:
Kai-Uwe Bux wrote:
>Sure. Define a function template:
[...]
Please, don't snip context that you are refering to:

template < typename ListType >
typename ListType::itera tor
s_erase ( ListType & the_list,
typename ListType::itera tor iter ) {
...
}

Thanks, that's just what I need. Unfortunately I have never worked with
templates in C and I just can't get the syntax for a call to that
function right. Could you give an example?
Since all types can be deduced from the arguments, the following should
suffice:

s_erase( my_list, my_iter );
>BTW: I think, such a function fills a much needed gap in your code base.

Yeah, it would really make the project look a whole lot cleaner :-)
Either you are great master of irony, or my hint was just too subtle.
Best

Kai-Uwe Bux

Mar 18 '08 #5
Kai-Uwe Bux schrieb:
Philip Mueller wrote:
>Kai-Uwe Bux wrote:
>>Sure. Define a function template:
template < typename ListType >
typename ListType::itera tor
s_erase ( ListType & the_list,
typename ListType::itera tor iter ) {
...
}

>Unfortunatel y I have never worked with
templates in C and I just can't get the syntax for a call to that
function right. Could you give an example?

Since all types can be deduced from the arguments, the following should
suffice:

s_erase( my_list, my_iter );
When I do this

list<intTest;
list<int>::iter ator iter;
iter = s_erase(Test, iter);

I get a compile error saying

undefined reference to `std::list<int, std::allocator< int::iterator
s_erase<std::li st<int, std::allocator< int >(std::list<int ,
std::allocator< int&, std::list<int, std::allocator< int::iterator)'

I find this very difficult to read, but even after reading it multiple
times I don't understand it.
Do you know where I can find introductory texts about templates?
>>BTW: I think, such a function fills a much needed gap in your code base.
Yeah, it would really make the project look a whole lot cleaner :-)

Either you are great master of irony, or my hint was just too subtle.
Maybe it was.

For clarification:

I need s_erase because I have a for-loop iterating over the list and
deleting objects that satisfy a given condition.[1]
Now, when I use the stl::list "erase()" method, it returns an iterator
to the next element.
In the next iteration the loop also increments the iterator so I have
skipped the Element after the one I deleted.
If you have a different, simpler idea, you're welcome to share it with
me :-)

Regards
Philip

[1]:
list<cShipShips ;
for (list<cShip>::i terator iS = Ships.begin(); iS != Ships.end(); iS++)
{
//This is the version that skips elements. I don't want that :-)
if (condition(iS))
iS = Ships.erase(iS) ;
}

Another possibility would be

if (condition(iS))
{
iS = Ships.erase(iS) ;
iS--;
}

but I don't think that's good code, especially because I need that
fragment at multiple locations in the program.
That's why I want a method for that.

if (condition(iS)) iS = s_erase(Ships, iS);
Mar 18 '08 #6
Philip Mueller wrote:
Kai-Uwe Bux schrieb:
>Philip Mueller wrote:
>>Kai-Uwe Bux wrote:
Sure. Define a function template:
template < typename ListType >
typename ListType::itera tor
s_erase ( ListType & the_list,
typename ListType::itera tor iter ) {
...
}

>>Unfortunate ly I have never worked with
templates in C and I just can't get the syntax for a call to that
function right. Could you give an example?

Since all types can be deduced from the arguments, the following should
suffice:

s_erase( my_list, my_iter );

When I do this

list<intTest;
list<int>::iter ator iter;
iter = s_erase(Test, iter);

I get a compile error saying

undefined reference to `std::list<int, std::allocator< int::iterator
s_erase<std::li st<int, std::allocator< int >(std::list<int ,
std::allocator< int&, std::list<int, std::allocator< int::iterator)'
Did you put the declaration of s_erase in a header and the implementation in
a cpp-file? If so, you would need a compiler that implements the export
keyword. For compilers that don't (which is the case for most of them),
template implementations need to go into the header file.
I find this very difficult to read, but even after reading it multiple
times I don't understand it.
Do you know where I can find introductory texts about templates?
I use

Vandervoorde and Josuttis: "C++ Templates: The Complete Guide"

but I don't know if that qualifies as an introductory text.

>>>BTW: I think, such a function fills a much needed gap in your code
base.
Yeah, it would really make the project look a whole lot cleaner :-)

Either you are great master of irony, or my hint was just too subtle.
Maybe it was.

For clarification:

I need s_erase because I have a for-loop iterating over the list and
deleting objects that satisfy a given condition.[1]
Now, when I use the stl::list "erase()" method, it returns an iterator
to the next element.
In the next iteration the loop also increments the iterator so I have
skipped the Element after the one I deleted.
If you have a different, simpler idea, you're welcome to share it with
me :-)
The standard idioms to remove elements from a list is:

for ( iterator iter = my_list.begin() ; iter != my_list.end(); ) {
if ( condition( *iter ) ) {
iter = my_list.erase( iter );
} else {
++ iter;
}
}

More concisely but requiring a function or function object you can use the
remove_if() member function:

my_list.remove_ if( predicate_objec t );

Regards
Philip

[1]:
list<cShipShips ;
for (list<cShip>::i terator iS = Ships.begin(); iS != Ships.end(); iS++)
{
//This is the version that skips elements. I don't want that :-)
if (condition(iS))
iS = Ships.erase(iS) ;
}

Another possibility would be

if (condition(iS))
{
iS = Ships.erase(iS) ;
iS--;
}

but I don't think that's good code, especially because I need that
fragment at multiple locations in the program.
That's why I want a method for that.

if (condition(iS)) iS = s_erase(Ships, iS);
The problem with those alternative versions is that they have some trouble
deleting the first element of the list.
Best

Kai-Uwe Bux

Mar 18 '08 #7
In article <64************ *@mid.uni-berlin.de>,
Philip Mueller <me@alienenpero r.DELETETHIS.de wrote:
Kai-Uwe Bux schrieb:
Philip Mueller wrote:
Kai-Uwe Bux wrote:
Sure. Define a function template:
template < typename ListType >
typename ListType::itera tor
s_erase ( ListType & the_list,
typename ListType::itera tor iter ) {
...
}

Unfortunately I have never worked with
templates in C and I just can't get the syntax for a call to that
function right. Could you give an example?
Since all types can be deduced from the arguments, the following should
suffice:

s_erase( my_list, my_iter );

When I do this

list<intTest;
list<int>::iter ator iter;
iter = s_erase(Test, iter);

I get a compile error saying

undefined reference to `std::list<int, std::allocator< int::iterator
s_erase<std::li st<int, std::allocator< int >(std::list<int ,
std::allocator< int&, std::list<int, std::allocator< int::iterator)'

I find this very difficult to read, but even after reading it multiple
times I don't understand it.
Do you know where I can find introductory texts about templates?
My guess is it is complaining because you put the definition of the
function in a cpp file other than the one using it. Take the code that
Kai gave you and paste it directly in a .h file.
>BTW: I think, such a function fills a much needed gap in your code base.
Yeah, it would really make the project look a whole lot cleaner :-)
Either you are great master of irony, or my hint was just too subtle.
Maybe it was.

For clarification:

I need s_erase because I have a for-loop iterating over the list and
deleting objects that satisfy a given condition.[1]
Now, when I use the stl::list "erase()" method, it returns an iterator
to the next element.
In the next iteration the loop also increments the iterator so I have
skipped the Element after the one I deleted.
If you have a different, simpler idea, you're welcome to share it with
me :-)
Ships.remove_if ( &condition );

The above will do what you describe below without much effort on your
part. You might have to modify condition to take a const reference
rather than a pointer.
[1]:
list<cShipShips ;
for (list<cShip>::i terator iS = Ships.begin(); iS != Ships.end(); )
{
if (condition(iS))
iS = Ships.erase(iS) ;
else
++iS;
}
I modified the code above so that it doesn't skip elements anymore.
Mar 18 '08 #8
Philip Mueller wrote:
Hi,

I am using multiple stl::list s of different types.

Now I want to write a function

list<type>::ite rator s_erase(list<ty pel, list<type>::ite rator it)

that takes an iterator and deletes the element it is pointing add, and
returns the iterator pointing to the predecessor of the erased
element.
like this:

return l.erase(it)--;

But I want this to work for any contained type. For clarification:
I have theses lists:

list<cShipShips ;
list<cProjectil eProjectiles;
list<cAsteroidA steroids;

And I want my function to work on all of these lists. Is that
possible?
You need to work around the possibility of your 'l's being empty,
or containing only one element (after which you're trying to use
post-decrement on the 'end', which is UB), but beyond that, what
is stopping you from making it a template?

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Mar 18 '08 #9
Kai-Uwe Bux wrote:
The standard idioms to remove elements from a list is:

for ( iterator iter = my_list.begin() ; iter != my_list.end(); ) {
if ( condition( *iter ) ) {
iter = my_list.erase( iter );
} else {
++ iter;
}
}
First of all, thanks for your suggestions Kai-Uwe.
This example makes perfect sense to me. But I have problems adapting it
to a special case:

for (iProj = Projectiles.beg in(); iProj != Projectiles.end (); iProj++)
for (iAst = Asteroids.begin (); iAst != Asteroids.end() ; iAst++)
if (iProj->DistanceTo(&*i Ast) <= iAst->getRadius())
{
iProj = Projectiles.era se(iProj);
iAst = Asteroids.erase (iAst);
}

What I mean to do here is test two list of objects for collisions
between an element from the "Projectile s" list and an element from the
"Asteroids" list (Collision detection via "DistanceTo ").
Then if there is such a collision, I want to delete both the projectile
and the asteroid.

Can someone give me a hint?

Regards
Philip

p.s.:
My best try so far is

for (iProj = Projectiles.beg in(); iProj != Projectiles.end ();)
{
iAst = Asteroids.begin ();
while (iAst != Asteroids.end()
&& iProj->DistanceTo(&*i Ast) iAst->getRadius())
iAst++;
if (iAst != Asteroids.end() )
{
iAst = Asteroids.erase (iAst);
iProj = Projectiles.era se(iProj);
}
else
iProj++;
}

There has to be a better way.
Mar 20 '08 #10

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

Similar topics

13
20503
by: Paras | last post by:
Hi What is the correct way to delete an element from STL list while iterating through the list list<A*> _ls; A * a; list<A*>::iterator si1;
2
2408
by: Barry Hynes | last post by:
G'Day folks, Have been working on this problem for quite some time and still no farther ahead. :( Here is my problem...bare with me i am very green :) I have to implement a Safe List, that is derived from the STL class List and uses exception handling.
4
2881
by: Christian Christmann | last post by:
Hi, I need an STL list and was thinking of putting the list in wrapper class. The reason for my decision is that you can much better perform consistency checks. For instance, I need a function to append a list to another. Using a wrapper class I could do something like:
8
4896
by: cpptutor2000 | last post by:
I am using an STL list to store data packets in a network simulator. The data packets are really C structs, which have other C structs inside them. These structs contain unsigned char arrays of various sizes, and some unsigned int values. There are no pointers values stored in these structs. I have a function, from inside of which I have a loop as follows: Please note that dataPacketStore is the name of the struct being stored. ...
5
4603
by: Allerdyce.John | last post by:
In STL list, is it safe to do this: list<A> aList; //private attribute of MyClass void MyClass:: aMethod() { list<A>::Iterator iter; for ( iter = aList.begin() ; iter != aList.end() ; iter++) { A a = (*iter);
6
6892
by: Allerdyce.John | last post by:
Hi, How can I Random access an element in a STL List if I have a pointer to that list? I know how to do that if I have a reference to a STL list, but how can I do that if I have a pointer to a STL List. void function (vector<int>& myLIst) { // access the first element of myList printf ("%d", myList);
6
2965
by: Jonathan | last post by:
Hi. I'm having trouble figuring out what I should be doing here. I'm trying to remove an object from a list. The function is: void Alive::FromRoom () { list<Alive>::iterator iter = room->living.begin(); while (iter != room->living.end()) {
3
2725
by: Christian Christmann | last post by:
Hi, reading the output of gprof for one of my projects, I found that the STL list assignment operator consumes a larger fraction of the program's execution time. The exact entry in gprof's output looks as follows: std::list<MyClass*, std::allocator<MyClass*::operator= (std::list<MyClass*, std::allocator<MyClass* const&) >
10
2783
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)
0
9602
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
9439
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,...
1
10017
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
9882
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...
1
7431
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
5467
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3987
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
3589
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2832
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.