C ++ 14中是否有可用的内置函数来查找数组中是否存在元素?
find()函数基于迭代器,用于矢量。但是对于数组呢?
答案 0 :(得分:3)
您仍然可以使用<algorithm>
中的std::find
。 input iterator是一个也由指针建模的概念,因此您可以使用指针作为std::find
的参数,如下所示:
#include <algorithm>
int main()
{
constexpr int N{10};
int a[N] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
return std::find(a, a + N, 5) != (a + N) ? 0 : 1;
}
答案 1 :(得分:1)
您可以使用STL中的非成员begin()
和end
:
#include <algorithm>
#include <iterator>
int main() {
int a[] = {0, 1, 2, 3, 4};
auto it = std::find(std::begin(a), std::end(a), 3);
if (it != std::end(a)) {
// do stuff with the found element it
}
}
它返回指向数组元素的指针,就像Ton van den Heuvel的答案一样。
此外,请不要忘记std::array
,它是围绕着简单数组的轻量级包装器:
#include <algorithm>
int main() {
std::array a = {0, 1, 2, 3, 4};
auto it = std::find(a.begin(), a.end(), 3);
if (it != std::end(a)) {
// do stuff with the found element it
}
}