Joan Venge Joan Venge - 2 months ago 24
C++ Question

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

All I wanna 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();

MSN MSN
Answer

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

std::find(vector.begin(), vector.end(), item) != vector.end()

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

#include <algorithm>

if ( std::find(vector.begin(), vector.end(), item) != vector.end() )
   do_this();
else
   do that();