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();
With boost you can use
any_of_equal
:Use find from the algorithm header of stl.I've illustrated its use with int type. You can use any type you like as long as you can compare for equality (overload == if you need to for your custom class).
As others have said, use the STL
find
orfind_if
functions. But if you are searching in very large vectors and this impacts performance, you may want to sort your vector and then use thebinary_search
,lower_bound
, orupper_bound
algorithms.Use the STL find function.
Keep in mind that there is also a find_if function, which you can use if your search is more complex, i.e. if you're not just looking for an element, but, for example, want see if there is an element that fulfills a certain condition, for example, a string that starts with "abc". (
find_if
would give you an iterator that points to the first such element).I use something like this...
...as that way it's actually clear and readable. (Obviously you can reuse the template in multiple places).