Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to find out if an item is present in a std::vector?

All I need to do is to check if an element exists in the vector, so I can manage each case.

if ( item_present )
do_this();
else
do_that();
by

2 Answers

akshay1995
You can use std::find from <algorithm>:

#include <algorithm>
#include <vector>
vector<int> vec;
//can have other data types instead of int but must same datatype as item
std::find(vec.begin(), vec.end(), item) != vec.end()

This returns a bool (true if present, false otherwise). With your example:

#include <algorithm>
#include <vector>

if ( std::find(vec.begin(), vec.end(), item) != vec.end() )
do_this();
else
do_that();
kshitijrana14
With boost you can use any_of_equal:
#include <boost/algorithm/cxx11/any_of.hpp>
bool item_present = boost::algorithm::any_of_equal(vector, element);

Login / Signup to Answer the Question.