1

Is there a way to delete an element from an STL container (be it list, vector, ...) only via an iterator pointing to the element to be deleted, but without providing the container object it resides in (i.e. without directly using the container memberfunction container<T>::iterator container<T>.erase(container<T>::iterator)?

(Follow-up to this question)

3
  • @LCsa You can use another member function like for example pop_back.:) Commented Jan 27, 2017 at 0:32
  • I see that from time to time and have often wondered, "What is the address of a non-breaking space?" Commented Jan 27, 2017 at 0:32
  • @VladfromMoscow The joke about it is not to use the actual container at all. :) Commented Jan 27, 2017 at 17:29

1 Answer 1

2

No, this is not possible.

Imagine what would have to happen in order for the standard to provide a way to do this. std::vector<T>::iterator could not be a simple T*. Instead it would have to contain enough information for the library to be able to "find" the vector to which it belongs, such as a pointer to the vector itself. Thus, if the standard imposed a requirement to make it possible to delete an element given only an iterator, it would force the standard library to add overhead that would slow down all users of the container.

Sign up to request clarification or add additional context in comments.

2 Comments

If you are dealing with ranges, you sort of can do this in the style of std::remove, by moving all of the elements up, provided you start with a range. You'll have a new range at the end though and likely would have to use std::vector<>::erase or similar afterwards though.
So, there is no way to do this, if I do not also provide the container the iterator points to? Do you have an idea of how to solve the problem (as described in the linked question?)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.