2

A very simple question but I couldn't find an answer. It would make awful lot of sense for it to be allowed but want to double-check.

std::vector<int> v(10, 0);
v.erase(v.end()); // allowed or not?
Violet Giraffe
  • 32,368
  • 48
  • 194
  • 335
  • Does this answer your question? [Erasing vector::end from vector](https://stackoverflow.com/questions/9590117/erasing-vectorend-from-vector) – Ken Y-N Nov 26 '21 at 07:39
  • @KenY-N: yes, that is the same question, but the answers here are better - I find them clearer, more to the point and easier to understand. I would rather mark the other one as duplicate. – Violet Giraffe Nov 26 '21 at 15:36

2 Answers2

4

An invalid position or range causes undefined behavior.

From here

The iterator pos must be valid and dereferenceable. Thus the end() iterator (which is valid, but is not dereferencable) cannot be used as a value for pos.

P0W
  • 46,614
  • 9
  • 72
  • 119
  • 1
    Well that sucks. Thank you. I wonder why they decided to go this way: makes `v.erase(std::find(v.begin(), v.end(), item))` invalid. – Violet Giraffe Sep 12 '13 at 18:10
  • @VioletGiraffe perhaps you are searching for the [erase-remove idiom](http://en.wikipedia.org/wiki/Erase-remove_idiom)? `v.erase(std::remove(v.begin(), v.end(), item), v.end());` – Fiktik Sep 12 '13 at 18:17
  • 1
    @Fiktik: hmm, perhaps. But looks like overkill for removing just a single item. – Violet Giraffe Sep 12 '13 at 18:17
  • 1
    @Fiktik No. The remove keeps searching the list for duplicates. If std::find works, then std::remove is an inefficient substitute. You only need to use std::remove when there are potential duplicates in the list. – srm Jan 14 '20 at 19:24
1

For the single argument overload it is NOT valid to pass end() to std::vector::erase, because the single argument overload will erase the element AT that position. There is no element at the end() position, since end() is one past the last element.

However, end() can be passed to the overload of erase that takes an Iterator range:

vec.erase(vec.begin(), vec.end())
Charles Salvia
  • 52,325
  • 13
  • 128
  • 140