0

So my doubt is simple, when we call erase() function for some range in a container,we know that the iterators following those element change (i'm talking about the iterators used to specify the range of the container as the arguments to the erase() function) But my question is does the iterators before that elements change too?

  • 2
    When in doubt consult [the reference](https://en.cppreference.com/w/cpp/container/vector/erase). No, it doesn't change the iterators before the point of erasure. – Lukas-T May 28 '20 at 15:58
  • They do not "change", they are invalidated. And it depends on the container. Some never invalidate iterators (except of the removed elements, obviously), – lvella May 28 '20 at 16:02
  • The standard library has quite a few containers. https://en.cppreference.com/w/cpp/container. It's best to look up each container's documentation to understand its behavior. – R Sahu May 28 '20 at 16:04
  • See the section titles *Erasure* in the accepted answer on the dupe target – NathanOliver May 28 '20 at 16:04
  • 1
    @NathanOliver That doesn't answer the question. In fact, I don't think the the standard even specifies the answer to this (sorry @churill, @RSahu!). I believe this question is basically "if I have `std::vector v{a,b,c,d,e};`, and I call `std::erase(v.begin()+2, v.begin()+4)`, I can observe the state of `v` during the call to `erase` (inside of `MyObj::~MyObj` and `MyObj::operator=`). During the call to `erase`, which iterators have been invalidated?" Now, I believe the best answer possible is "This is unspecified. To be safe, don't touch `v` during a call to `erase`" – HTNW May 28 '20 at 16:09

1 Answers1

0

when we call erase() function for some range in a container,we know that the iterators following those element change

I think you mean that those iterators become invalid. Note that this is not universally true for all containers. For example, iterators to elements after the erased one in std::list remain valid.

Which iterators are invalidated and when depends on the container. You'll need to consult the documentation of the container that you are using. One thing common to all standard containers is that iterators to the erased element are invalidated.

eerorika
  • 232,697
  • 12
  • 197
  • 326