Finding an item in std::vector
I want to check whether an element exists in the vector or not, so I can deal with each case. I came across this formula :
#include <algorithm>
if ( std::find(vector.begin(), vector.end(), item) != vector.end() )
do_this();
else
do that();
I dont understand why do we need vector.end() at the end, isnt find(vector.begin(), vector.end(), item) enough to find the element ?
std::find(vector.begin(), vector.end(), item)
will return an Iterator, so by comparing it to
vector.end()
you are actually checking to see if such an iterator with that item exists.
I dont understand why do we need vector.end() at the end, isnt find(vector.begin(), vector.end(), item) enough to find the element ?
The result of find
on failing to find a match is an iterator pointing to the end of the range provided, and there's nothing particularly special about end iterators that allow them to be compared like a boolean state.
find
was designed to be a general-purpose algorithm that works on a wide variety of containers (including even those potentially outside the standard library). It's also designed to do simply more than return whether an element was found or not -- it returns an iterator pointing to the item if found. As a result, it doesn't return null or anything like that if it fails to find the element. It returns iterators.
If you really do this kind of thing a lot (and I only recommend doing anything like this if you do, since you're introducing something foreign to daily code), you can do something like this:
/// @return True if `val` is found in `[first, last)`
template <class Iterator, class Element>
bool contains(Iterator first, Iterator last, const Element& val)
{
return std::find(first, last, val) != last;
}
...
if (contains(vector.begin(), vector.end(), item))
do_this();
else
do_that();
It's checking whether the value was actually found or not.
std::find() returns an iterator to the first element in the query range.
If the returned value is equal to vector.end() that means it didn't find the item.
See this for more information.