例如,我有这个数组:
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
未找到。
关于c++ - 如何检查给定的 int 是否存在于数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19299508/