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


Question

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();
1
575
11/2/2017 8:43:13 PM

Accepted Answer

You can use std::find from <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();
855
4/4/2019 10:57:12 AM

As others have said, use the STL find or find_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 the binary_search, lower_bound, or upper_bound algorithms.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon