39

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,600
  • 9
  • 48
  • 75
yegor256
  • 102,010
  • 123
  • 446
  • 597

3 Answers3

83

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
  • 219,715
  • 46
  • 258
  • 445
Vladimir
  • 170,431
  • 36
  • 387
  • 313
  • 5
    +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
  • 91,295
  • 49
  • 239
  • 345
Brian R. Bondy
  • 339,232
  • 124
  • 596
  • 636
7

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
  • 91,295
  • 49
  • 239
  • 345