HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcppCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howfindstdvectoroutpresentitem

Problem

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();

Solution

You can use std::find from ``:

#include 
#include 
vector 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 an iterator to the first element found. If not present, it returns an iterator to one-past-the-last. With your example:

#include 
#include 

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

Code Snippets

#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()
#include <algorithm>
#include <vector>

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

Context

Stack Overflow Q#571394, score: 1251

Revisions (0)

No revisions yet.