C++ 14中是否有任何内置函数可用于查找数组中是否存在元素?
find()函数基于迭代器,用于向量。但是在数组的情况下呢?
发布于 2018-07-10 13:38:24
发布于 2018-07-11 06:20:56
您可以使用来自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
}
}https://stackoverflow.com/questions/51266644
复制相似问题