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

How can I check if given int exists in array?

本文关键字:存在 是否 int 数组 何检查 检查      更新时间:2023-10-16

例如,我有这个数组:

int myArray[] = { 3, 6, 8, 33 };

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

我是否必须编写自己的函数并循环数组,或者现代 c++ 中是否有相当于 PHP 中的in_array

您可以使用

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);
}

std::find 返回一个迭代器到第一次出现x,或者一个迭代器到超过范围末尾x如果未找到。

我认为您正在寻找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;
});

如果你想知道元素在哪里,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
}

试试这个

#include <iostream>
#include <algorithm>

int main () {
  int myArray[] = { 3 ,6 ,8, 33 };
  int x = 8;
  if (std::any_of(std::begin(myArray), std::end(myArray), [=](int n){return n == x;}))   {
      std::cout << "found match/" << std::endl;
  }
  return 0;

}

您几乎不必用C++编写自己的循环。 在这里,你可以使用 std::find。

const int toFind = 42;
int* found = std::find (myArray, std::end (myArray), toFind);
if (found != std::end (myArray))
{
  std::cout << "Found.n"
}
else
{
  std::cout << "Not found.n";
}

std::end需要C++11。 没有它,你可以用以下命令找到数组中的元素数量:

const size_t numElements = sizeof (myArray) / sizeof (myArray[0]);

。结尾为:

int* end = myArray + numElements;
int index = std::distance(std::begin(myArray), std::find(begin(myArray), end(std::myArray), VALUE));

如果未找到,则返回无效索引(数组的长度(。

你确实需要遍历它。C++ 在处理基元类型数组时没有实现任何更简单的方法来执行此操作。

另请参阅此答案:C++检查数组中是否存在元素