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.
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.
In Java 8, we can use the Collection#removeIf API to remove items from a List while iterating it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With