33

Possible Duplicate:
How to find an item in a std::vector?

This is what I'm looking for:

#include <vector>
std::vector<int> foo() {
  // to create and return a vector
  return std::vector<int>();
}
void bar() {
  if (foo().has(123)) { // it's not possible now, but how?
    // do something
  }
}

In other words, I'm looking for a short and simple syntax to validate the existence of an element in a vector. And I don't want to introduce another temporary variable for this vector. Thanks!

Amir
  • 10,056
  • 9
  • 43
  • 71
yegor256
  • 97,508
  • 114
  • 426
  • 573

3 Answers3

73

Unsorted vector:

if (std::find(v.begin(), v.end(),value)!=v.end())
    ...

Sorted vector:

if (std::binary_search(v.begin(), v.end(), value)
   ...

P.S. may need to include <algorithm> header

sbi
  • 212,637
  • 45
  • 247
  • 432
Vladimir
  • 169,112
  • 36
  • 383
  • 312
  • 4
    +1 for the P.S., I got the above code from various sources but did not know to include the header and hence my code was giving error. Thank You. – dc95 Jan 24 '15 at 20:25
19
int elem = 42;
std::vector<int> v;
v.push_back(elem);
if(std::find(v.begin(), v.end(), elem) != v.end())
{
  //elem exists in the vector
} 
Prasoon Saurav
  • 88,492
  • 46
  • 234
  • 343
Brian R. Bondy
  • 327,498
  • 120
  • 583
  • 623
6

Try std::find

vector<int>::iterator it = std::find(v.begin(), v.end(), 123);

if(it==v.end()){

    std::cout<<"Element not found";
}
Prasoon Saurav
  • 88,492
  • 46
  • 234
  • 343