All I want to do is to check whether an element exists in the vector or not, so I can deal with each case.
if ( item_present )
do_this();
else
do_that();
All I want to do is to check whether an element exists in the vector or not, so I can deal with each case.
if ( item_present )
do_this();
else
do_that();
You can use the
find
function, found in thestd
namespace, iestd::find
. You pass thestd::find
function thebegin
andend
iterator from the vector you want to search, along with the element you're looking for and compare the resulting iterator to the end of the vector to see if they match or not.You're also able to dereference that iterator and use it as normal, like any other iterator.
You can try this code:
You can use count too. It will return the number of items present in a vector.
Using Newton C++ it's easier, self-documented and faster than with std::find because of return a bool directly.
I think it's obvious what the functions do.
You can use
std::find
from<algorithm>
:This returns a bool (
true
if present,false
otherwise). With your example: