Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 995
The Vivandiere Avatar asked Oct 17 '25 09:10

The Vivandiere


2 Answers

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.

like image 135
Cameron Avatar answered Oct 19 '25 00:10

Cameron


Algorithms apply to ranges, which are defined by a pair of iterators. Those iterators are passed as arguments to the algorithm. The first iterator points at the first element in the range, and the second argument points at one past the end of the range. Algorithms that can fail return a copy of the past-the-end iterator when they fail. That's what std::find does: if there is no matching element it returns its second argument.

Note that the preceding paragraph does not use the word "container". Containers have member functions that give you a range that you can use to get at the elements of the container, but there are also ways of creating iterators that have no connection to any container.

like image 40
Pete Becker Avatar answered Oct 19 '25 00:10

Pete Becker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!