Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/136.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在一行中检查std::vector中是否存在元素?_C++_Vector - Fatal编程技术网

C++ 如何在一行中检查std::vector中是否存在元素?

C++ 如何在一行中检查std::vector中是否存在元素?,c++,vector,C++,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 } } #包括 std:

可能重复:

这就是我要找的:

#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
  }
}
#包括
std::vector foo(){
//创建并返回向量的步骤
返回std::vector();
}
空条(){
如果(foo().has(123)){//现在不可能了,但是怎么可能呢?
//做点什么
}
}
换句话说,我正在寻找一种简短的语法来验证向量中元素的存在性。我不想为这个向量引入另一个临时变量。谢谢

int元素=42;
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
} 
std::向量v; v、 推回(elem); if(std::find(v.begin(),v.end(),elem)!=v.end()) { //元素存在于向量中 }
未排序向量:

if (std::find(v.begin(), v.end(),value)!=v.end())
    ...
if (std::binary_search(v.begin(), v.end(), value)
   ...
排序向量:

if (std::find(v.begin(), v.end(),value)!=v.end())
    ...
if (std::binary_search(v.begin(), v.end(), value)
   ...
备注可能需要包括
标题尝试

vector::iterator it=std::find(v.begin(),v.end(),123);
如果(it==v.end()){

std::coutsure if()条件应该是!=?+1对于P.S.,我从各种来源获得了上述代码,但不知道要包含头,因此我的代码给出了错误。谢谢。