-4

This accepted answer states the following code:

std::find(vector.begin(), vector.end(), item)!=vector.end()

The first part I understand, we are going to find item between the begin and end of vector. But why the !=vector.end(). Something like: "if the end of the vector does not equal what is found"? Should this code be in an if statement?

Community
  • 1
  • 1
Tim
  • 1,585
  • 1
  • 18
  • 23
  • 3
    Have you actually checked the documentation for std::find? – Columbo Jan 22 '15 at 20:30
  • 1
    Yes, the result of the expression is a bool. It should either be an if statement or store the result in a variable. – mbgda Jan 22 '15 at 20:31
  • 1
    http://en.cppreference.com/w/cpp/algorithm/find – Retired Ninja Jan 22 '15 at 20:31
  • 3
    This question is not asking for an off-site resource. Closevoter, please lay off the drugs while using SO. Ta. – Lightness Races in Orbit Jan 22 '15 at 20:32
  • 2
    The above expression is meant as a replacement for `item_present` in the question you've linked to – Praetorian Jan 22 '15 at 20:32
  • 1
    Guys, I think he's saying the line of code is literally what's above, which is an expression for which the result is thrown away. – mbgda Jan 22 '15 at 20:33
  • @mbgda maybe not only guys are here, but I think you are right. Tim don't take that answer literally! – mip Jan 22 '15 at 20:36
  • If you read the question that the linked answer is from it's pretty clear that it was meant to be a substitute into the question code. There's also another answer that shows complete usage in code. – Retired Ninja Jan 22 '15 at 20:38
  • Yeah @mbgda please be gender-neutral and check your privilege at all times!! Thanks!! :-) – Lightness Races in Orbit Jan 22 '15 at 20:39
  • +1 This question is not lazy or stupid but is asking _why_ an end iterator has these semantics and for a way to make that intuitive. Nothing wrong with it. – Lightness Races in Orbit Jan 22 '15 at 20:39
  • @RetiredNinja I didn't see the first line that links what you're referring to until you pointed it out. This definitely could have been 30 seconds with google instead of being posted here. – mbgda Jan 22 '15 at 20:40

1 Answers1

5

std::vector::end returns a "special" iterator. It does not give you the last element, but one past the end.

It is also used to indicate "no match" or "no element", much like you might have used "-1" to signal an error condition back in the 1970s.

That's what you're seeing here.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055