Hrisip
Hrisip

Reputation: 920

std::vector erasing with first iterator after last

What will happen when erasing a range whose first iterator is after the last iterator?

std::vector<int> v{1,2};

v.erase(
    v.begin() + 1,
    v.begin()
);

What about other containers?

Upvotes: 1

Views: 117

Answers (1)

Bitwize
Bitwize

Reputation: 11220

It's undefined behavior to call erase with an invalid range on any container. In practice, it will generally crash the program if you are lucky, or smash adjacent memory if you're unlucky.

This should be true for just about any API that accepts an iterator range. If a range is invalid, there is no way for the underlying code/algorithm to be aware of what the stopping condition actually is.


Iterator ranges delimit the start and end of a range for any input or algorithm. The end iterator is always used to indicate the completion of that range, and must always be reachable by repeatedly incrementing the first iterator (e.g. by calling operator++).

Most algorithms make use of operator!= to detect the completion of the range, from the LegacyInputIterator requirement. Some ranges may optionally make use of the distance between iterators if that that range is a LegacyRandomAccessIterator.

In either case, this detection requires that the first iterator be before the last, otherwise code like:

for (auto it = first; first != last; ++first) { ... }

will never reach the end of the range, and similarly:

auto distance = last - first;

will return an incorrect value for the distance between iterators.

Upvotes: 5

Related Questions