tags:

views:

67

answers:

3

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!

A: 
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
} 
Brian R. Bondy
+4  A: 

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

Vladimir
+1  A: 

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
Surely the if() condition should be != ?
JBRWilkinson
Yes! edited....
Prasoon Saurav