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();
Here's a function that will work for any Container:
Note that you can get away with 1 template parameter because you can extract the
value_type
from the Container. You need thetypename
becauseContainer::value_type
is a dependent name.If your vector is not ordered, use the approach MSN suggested:
If your vector is ordered, use binary_search method Brian Neal suggested:
binary search yields O(log n) worst-case performance, which is way more efficient than the first approach. In order to use binary search, you may use qsort to sort the vector first to guarantee it is ordered.
Bear in mind that, if you're going to be doing a lot of lookups, there are STL containers that are better for that. I don't know what your application is, but associative containers like std::map may be worth considering.
std::vector is the container of choice unless you have a reason for another, and lookups by value can be such a reason.
In C++11 you can use
any_of
. For example if it is avector<string> v;
then:If you wanna find a string in a vector:
Another sample using C++ operators.