Search code examples
c++algorithmc++11iterator

What does std::find return if element not found


As per documentation, std::find returns

last

if no element is found. What does that mean? Does it return an iterator pointing to the last element in the container? Or does it return an iterator pointing to .end(), i.e. pointing outside the container? The following code prints 0, which is not an element of the container. So, I guess std::find returns an iterator outside the container. Could you please confirm?

int main()
{
    vector<int> vec = {1, 2,3, 1000, 4, 5};
    auto itr = std::find(vec.begin(), vec.end(), 456);
    cout << *itr;
}

Solution

  • last is the name of second parameter to find. It doesn't know what kind of container you're using, just the iterators that you give it.

    In your example, last is vec.end(), which is (by definition) not dereferenceable, since it's one past the last element. So by dereferencing it, you invoke undefined behaviour, which in this case manifests as printing out 0.