Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing an element from a list with only its iterator

Is it possible to remove an element from an std::list if you have only the iterator that points to the element you want to remove? I have a large amount of functions that take iterators to list elements, and it would be a huge inconvenience to have to pass the owning list to every one of them.

like image 815
Seth Carnegie Avatar asked Jul 30 '11 17:07

Seth Carnegie


People also ask

How do you remove an element from a list while iterating?

If you want to delete elements from a list while iterating, use a while-loop so you can alter the current index and end index after each deletion.

Can we remove element from list while iterating Java?

In Java 8, we can use the Collection#removeIf API to remove items from a List while iterating it.


1 Answers

Edit:

You cant with a single iterator.

If you have the begin/end iterators, you could use the std::remove algorithm to move all the elements you want to erase to the end, and delete them at a later point.

If you don't, or the above isn't feasible with your current design, i'd recommend altering your functions to take a std::pair<std::list<T>, std::list<T>::iterator> or something like that.

like image 103
Node Avatar answered Sep 28 '22 11:09

Node