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!
Try std::find
vector<int>::iterator it = std::find(v.begin(), v.end(), 123);
if(it==v.end()){
std::cout<<"Element not found";
}
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
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
}
Source: Stackoverflow.com