Seth Carnegie
Seth Carnegie

Reputation: 75130

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.

Upvotes: 8

Views: 1567

Answers (6)

Catskul
Catskul

Reputation: 19230

While others have mentioned that you can't do it, I think I can offer as to why.

I believe the specific technical reason (rather than design reason) is that lists do some upkeep, like keeping track of size for example, which require that certain actions have to be passed through them to allow that upkeep.

It's for this reason that any hack that might be offered would likely fail.

Upvotes: 1

Mark B
Mark B

Reputation: 96233

You can't do that with the standard library, but you can use Boost's intrusive list http://www.boost.org/doc/libs/1_37_0/doc/html/boost/intrusive/list.html which has such an interface.

Upvotes: 3

Node
Node

Reputation: 3509

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.

Upvotes: 3

Daniel
Daniel

Reputation: 31559

You can do this manually. iterator exposes _M_node as the current node. you can do something like:

itr._M_node->_M_prev->_M_next = itr._M_node._M_next;

Upvotes: -1

sbi
sbi

Reputation: 224039

No, you can't. Iterators are light-weight objects modeled after pointers and do not carry a reference to the container they refer to. (Although some implementations do so internally in Debug mode.)

Just as you cannot "remove" an object from an array when all you have is a pointer into the array, you cannot remove an object from a container without also having access to the container.

Upvotes: 3

Andr&#233; Caron
Andr&#233; Caron

Reputation: 45239

No, this is not possible. As its name suggests, an iterator's job is to iterate over the elements of a sequence. Check out the SGI page on iterators for a summary of iterator design in the C++ standard library.

Upvotes: 0

Related Questions