答案:std::binary_search适用于判断元素存在性,手写二分更灵活可返回位置或处理复杂逻辑。1. std::binary_search使用简单但仅返回bool;2. 手写实现可获取索引、支持自定义比较;3. 标准库函数易用安全,手写适合特殊需求;4. 推荐优先使用标准库以保证正确性和可维护性。

二分查找是一种在有序数组中快速定位目标值的高效算法,时间复杂度为 O(log n)。C++ 提供了标准库函数 binary_search,同时也支持手动实现二分查找。本文将对比 std::binary_search 与手写二分查找的用法、优劣和适用场景。
std::binary_search 是 C++ 标准库中的一个算法函数,定义在 <algorithm> 头文件中,用于判断某个值是否存在于有序区间内。
基本语法:bool found = std::binary_search(begin, end, value);
它返回一个布尔值:如果找到目标值则返回 true,否则返回 false。
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <algorithm>
#include <vector>
<p>int main() {
std::vector<int> arr = {1, 3, 5, 7, 9};
if (std::binary_search(arr.begin(), arr.end(), 5)) {
std::cout << "找到了 5\n";
}
return 0;
}注意:必须保证容器已排序,否则结果未定义。
手动实现可以更灵活地控制行为,比如返回索引、查找第一个/最后一个匹配位置等。
基础版本(返回是否存在):
bool binarySearch(const std::vector<int>& arr, int target) {
int left = 0, right = arr.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) return true;
else if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return false;
}进阶版本(返回插入位置或首个位置):
例如,想找到目标值第一次出现的位置:
int lowerBound(const std::vector<int>& arr, int target) {
int left = 0, right = arr.size();
while (left < right) {
int mid = left + (right - left) / 2;
if (arr[mid] < target) left = mid + 1;
else right = mid;
}
return left;
}这个版本类似于 std::lower_bound,可用于处理重复元素的情况。
从多个维度比较两者的差异:
另外,标准库还提供 std::lower_bound 和 std::upper_bound,分别用于查找“第一个不小于”和“第一个大于”目标值的位置,配合使用能实现更多高级操作。
根据实际需求选择合适的方式:
基本上就这些。标准库已经非常强大,大多数情况下推荐优先使用 std::binary_search 或相关函数,只有在有特殊需求时才手写实现。正确性和可维护性往往比微小的性能提升更重要。
以上就是C++如何实现二分查找_C++ binary_search函数与手写算法对比的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号