find function element at the end

If the element I am trying to find using the find function is at the end of a vector, from what I understood, is it true that there isn´t really a way for me to tell if I found it?
end() returns an iterator to the position after the last element.

Look at the picture here: https://en.cppreference.com/w/cpp/container/vector/end

So there is no ambiguity. An iterator to the last element is not the same as the end iterator.
Last edited on
So the [pseudo] code may looks like this:
1
2
3
4
5
  it = find (begin, end, x);
  if (it != end)
    std::cout << "Element found\n";
  else
    std::cout << "Element not found\n";
is it true that there isn´t really a way for me to tell if I found it (ed: last element)?

It is possible using iterator arithmetic.
1
2
  if (iter+1 == end())
    cout << "found last element" << endl;


Ed: I think there may be some confusion here over the use of last. The declaration for std::find is:
1
2
template<class InputIterator, class T>
  InputIterator find (InputIterator first, InputIterator last, const T& val);

The range searched is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.

When searching the entire vector, the idiom is (as coder777 showed):
1
2
3
    iter = std::find vec.begin(); vec.end(); val);
    if (iter == end()
        //  Not found 
Last edited on
Topic archived. No new replies allowed.