check if a std::vector contains a certain object?

jmasterx picture jmasterx · Aug 10, 2010 · Viewed 485.3k times · Source

Is there something in <algorithm> which allows you to check if a std:: container contains something? Or, a way to make one, for example:

if(a.x == b.x && a.y == b.y)
return true;

return false;

Can this only be done with std::map since it uses keys?

Thanks

Answer

You picture You · Aug 10, 2010

Checking if v contains the element x:

#include <algorithm>

if(std::find(v.begin(), v.end(), x) != v.end()) {
    /* v contains x */
} else {
    /* v does not contain x */
}

Checking if v contains elements (is non-empty):

if(!v.empty()){
    /* v is non-empty */
} else {
    /* v is empty */
}