【发布时间】:2018-12-18 09:11:32
【问题描述】:
C++ 14 中是否有任何内置函数可用于查找数组中是否存在元素?
find() 函数基于迭代器并用于向量。但是数组呢?
【问题讨论】:
C++ 14 中是否有任何内置函数可用于查找数组中是否存在元素?
find() 函数基于迭代器并用于向量。但是数组呢?
【问题讨论】:
您仍然可以使用 std::find 中的 <algorithm> 来实现此目的。 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;
}
【讨论】:
您可以使用 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
}
}
【讨论】: