std::find要求迭代器而非长度,对int arr[5]应传首尾指针如arr与arr+5或用std::begin/ end;传长度会编译错误;返回end迭代器而非nullptr,使用前需判断。

std::find 要求迭代器,原生数组不能直接传
直接对 int arr[5] 调用 std::find(arr, 5, 42) 是错的 —— 第二个参数必须是迭代器(指针),不是长度。C++ 不会自动把数组长度转成结束指针。
正确做法是传入首尾指针:std::find(arr, arr + 5, 42)。注意 arr + 5 指向末尾后一位,符合左闭右开区间约定。
常见错误现象:error: no matching function for call to 'find',往往是因为传了整数当迭代器,或类型不匹配(比如传 const int* 给非 const 版本)。
用 std::begin / std::end 避免硬编码长度
硬写 arr + N 容易出错,尤其数组大小变化时。推荐用标准库辅助函数:
立即学习“C++免费学习笔记(深入)”;
-
std::find(std::begin(arr), std::end(arr), 42)—— 适用于 C++11 及以上、已知数组大小的栈上数组 -
std::begin()和std::end()对原生数组推导出正确的指针类型,且编译期检查数组维度 - 不适用于动态分配的
new int[5]或函数参数中的int arr[](退化为指针,丢失大小信息)
查不到时返回的是 end 迭代器,不是 nullptr
std::find 找不到元素时返回第二个参数(即 end 迭代器),不是空指针也不是 -1。拿结果直接解引用前必须判断:
auto it = std::find(std::begin(arr), std::end(arr), 42);
if (it != std::end(arr)) {
std::cout << "found: " << *it << "\n";
}
常见坑:if (it) 编译不过(指针才能隐式转 bool);if (*it) 会崩溃(未检查就解引用);if (it == nullptr) 类型不匹配。
性能和替代方案:数组小就别纠结,大数组考虑排序+二分
std::find 是线性遍历,O(n) 时间。它不关心数组是否有序,也不做任何优化。
- 如果数组固定且较大(如 >1000 元素),且查找频繁,先
std::sort再用std::binary_search或std::lower_bound更快 - 如果只是偶尔查一两次,或者数组很小(std::find 简单直接,无额外开销
- 注意:
std::find对std::array和std::vector同样适用,接口一致,但底层都是顺序扫描
容易被忽略的一点:std::find 比较用的是 operator==,自定义类型必须提供可访问的该运算符,否则编译失败。


















