C++ 如何用一句话检查 std::vector 中元素的存在?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3246863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 12:24:57  来源:igfitidea点击:

How can I check for existence of element in std::vector, in one sentence?

c++

提问by yegor256

Possible Duplicate:
How to find an item in a std::vector?

可能的重复:
如何在 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!

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

回答by Vladimir

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

PS 可能需要包含<algorithm>标题

回答by Brian R. Bondy

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
} 

回答by Prasoon Saurav

Try std::find

尝试 std::find

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

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

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