开发者

How can I check for existence of element in std::vector, in one line? [duplicate]

This question already has answers here: Closed 12 years ago.

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!


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
} 


Try std::find

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

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

    std::cout<<"Element not found";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜