gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:06:39 26 4
gpt4 key购买 nike

例如,我有这个数组:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com