如何在一个句子中检查std :: vector中元素的存在?

时间:2010-07-14 14:00:48

标签: c++

  

可能重复:
  How to find an item in a std::vector?

这就是我要找的:

#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
  }
}

换句话说,我正在寻找一种简短的语法来验证向量中元素的存在。我不想为这个向量引入另一个临时变量。谢谢!

3 个答案:

答案 0 :(得分:36)

未分类的矢量:

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

排序矢量:

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

P.S。可能需要包含<algorithm>标题

答案 1 :(得分:7)

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
} 

答案 2 :(得分:1)

尝试std::find

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

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

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