Does std::find on empty vector cause undefined behaviour?

Viewed 2295

trying to find an info on what happens if an empty vector used during std::find but didn't had much luck finding any info.

My question is, if an empty vector passed to std::find, is the return value always a nullptr or is it undefined behaviour?

  std::vector<int> someDataContainer;
  auto it = std::find(someDataContainer.begin(), someDataContainer.end(), 1);
4 Answers

The return value of find when the element is not present is the end iterator:

[alg.find] (emphasis mine):

Let E be:

  • *i == value for find,
  • [...]

Returns: The first iterator i in the range [first, last) for which E is true. Returns last if no such iterator is found.

This includes the element not being present because the range is empty.

An empty vector will have begin() == end() so std::find will just return immediately and return end(). No undefined behavior here.

It doesn't matter if the container is empty or not, the std::find will return the end iterator if the element is not found.

And in an empty container no element will be found.

In short: It's all well-defined and normal.

It is documented on here and here. If the the element cannot be found last is returned, i.e. in your case it will point to someDataContainer.end().

Related