如何检查数组中是否存在给定的int?

rsk*_*k82 18 c++ arrays

例如,我有这个数组:

int myArray[] = { 3, 6, 8, 33 };
Run Code Online (Sandbox Code Playgroud)

如何检查给定变量x是否在其中?

我是否必须编写自己的函数并循环数组,还是在现代c ++中与in_arrayPHP 相当?

jua*_*nza 39

你可以使用std::find这个:

#include <algorithm> // for std::find
#include <iterator> // for std::begin, std::end

int main () 
{
  int a[] = {3, 6, 8, 33};
  int x = 8;
  bool exists = std::find(std::begin(a), std::end(a), x) != std::end(a);
}
Run Code Online (Sandbox Code Playgroud)

std::find将迭代器返回到第一个匹配项x,或者将迭代器返回到范围的结尾(如果x未找到).

  • 或者简单地说:`bool exists = std :: any_of(std :: begin(array),std :: end(array),[&](int i){return i == x;});` (2认同)
  • 如果你不在C++ 11上,那么`std :: find`就不错了.然后`s​​td:begin`和`std:end`只是C++ 11. (2认同)

Zac*_*and 15

我认为你正在寻找std::any_of,它会返回一个真/假的答案来检测一个元素是否在一个容器中(数组,向量,双端队列等)

int val = SOME_VALUE; // this is the value you are searching for
bool exists = std::any_of(std::begin(myArray), std::end(myArray), [&](int i)
{
    return i == val;
});
Run Code Online (Sandbox Code Playgroud)

如果你想知道元素的位置,std::find将返回一个迭代器到第一个元素,匹配你提供的任何条件(或你给它的谓词).

int val = SOME_VALUE;
int* pVal = std::find(std::begin(myArray), std::end(myArray), val);
if (pVal == std::end(myArray))
{
    // not found
}
else
{
    // found
}
Run Code Online (Sandbox Code Playgroud)