如何检查数组中是否存在给定的 int
How can I check if given int exists in array?
例如,我有这个数组:
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++检查数组中是否存在元素
相关文章:
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 有了gcc,是否可以链接库,但前提是它存在
- gcc和clang在表达式是否为常量求值的问题上存在分歧
- 如何检查QList中是否存在值
- 根据某个函数是否存在启用模板
- 地图计数确实很重要,或者只是检查是否存在
- C++中是否存在 std::conditional 的懒惰等价物?
- 无论如何,我可以确定构造函数是否存在吗?
- COM :是否可以查看是否存在对我的某个 COM 对象的进程外引用?我可以释放它吗?
- 堆分配的对象是否存在永不为空的唯一所有者?
- 扩展类中的可选 vir 函数,测试它在运行时是否存在
- 模板化检查是否存在带有参数列表的类成员函数?
- 是否存在包含负号的isdigit函数(过载)
- 如何巧妙地编写两个函数——一个用于检查是否存在解决方案,另一个用于获取所有解决方案
- 检查编译时是否存在静态函数
- 向量是否存在行主要形式?
- 检查 TinyXML 中的元素是否存在
- 检测是否存在具有 C++17 的类成员
- 虚拟继承中是否存在多重继承?
- 我遇到了这个代码片段,不明白. 它递归检查 C++ 字符串中是否存在大写字符