Question

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?
Was it helpful?

Solution

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.

OTHER TIPS

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())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top