Series Article of cpp -- 06

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

Posted by OUC_LiuX on October 7, 2021

From StackOverlow

You can use std::find from :

#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 example:

#include <algorithm>
#include <vector>

if ( std::find(vec.begin(), vec.end(), item) != vec.end() )
   do_this();
else
   do_that();