7

I've want to erase the elements of the std::map from beginIt to endIt. erase function returns the iterator to the element that follows the last element removed. isn't it endIt ? Why the erase returns iterator ?

auto it = m_map.erase(beginIt, endIt);
Gevorg Adamyan
  • 111
  • 1
  • 7

2 Answers2

9

It's a useful feature that the C++ standard library adopts for all its containers.

One good use in particular is when you are deleting a set of elements subject to a constraint and you are iterating over the whole container. Obviously deleting something from a container invalidates the iterator that you passed. To return the next candidate iterator is useful.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • It is always true only only for single-argument functions and for two-arguments for some containers. Two-argument `erase` on map does not invalidate `endIt` – Revolver_Ocelot Mar 24 '16 at 19:53
  • It is not useful for range erase on map in any way. – SergeyA Mar 24 '16 at 19:54
  • @SergeyA Except when you want to do something like erase all keys bigger/smaller than a value. – Barry Mar 24 '16 at 20:10
  • @Barry, not sure what do you mean. `erase() ` needs either key or iterators. To do something like you are saying you first need to use `lower_bound`, and than use resulting iterators. – SergeyA Mar 24 '16 at 20:28
  • 1
    @SergeyA Please stop commenting. That last one doesn't even mean anything. Yes of course the iterators don't just conjure out of thin air. – Barry Mar 24 '16 at 20:29
  • @Barry, I got your comment in the sense that the return value of two-arguments `std::map::erase` would be useful when you want to erase all keys bigger than X. How exactly is it going to be useful? And unless it is, it is you who's comments do not mean anything. – SergeyA Mar 24 '16 at 20:33
2

I believe this is due to trying to unify function calls across the standard container types. For example, in an std::vector the returned iterator is not the same as endIt

kmdreko
  • 42,554
  • 6
  • 57
  • 106