std::binary_search要求容器已有序且只返回bool值;未排序则结果不可预测,需先调用std::sort;降序查找需传std::greater{};定位需用lower_bound/upper_bound等函数。

binary_search 要求容器必须有序
std::binary_search 不会帮你排序,它只在已排序的范围上做 O(log n) 查找。如果你传入一个乱序 std::vector,结果不可预测——大概率返回 false,即使目标值存在。
常见错误是:往 vector 里 push 一堆数,没调 std::sort 就直接 binary_search,然后纳闷“为啥找不到”。
- 升序查找:确保用
std::sort(v.begin(), v.end())或初始化时就有序 - 降序查找:得显式传自定义比较器,比如
std::binary_search(v.begin(), v.end(), x, std::greater{}) - 迭代器范围必须合法——
first不能超过last,否则 UB(未定义行为)
binary_search 只返回 bool,不返回位置
很多人误以为它像 Python 的 bisect_left,其实 std::binary_search 只告诉你“有没有”,不告诉你“在哪”。要获取下标或迭代器,得换函数:
- 找第一个 ≥ x 的位置:用
std::lower_bound - 找第一个 > x 的位置:用
std::upper_bound - 想同时拿到区间 [first, last) 内所有 x?用
std::equal_range
例如:
auto it = std::lower_bound(v.begin(), v.end(), x);
if (it != v.end() && *it == x) { /* 找到了,it 是第一个匹配位置 */ }
立即学习“C++免费学习笔记(深入)”;
注意迭代器类型和 const 正确性
binary_search 接收的是任意随机访问迭代器(vector::iterator、array::const_iterator 都行),但你得保证传进去的迭代器类型一致、指向同一容器。
- 对
const vector,只能用const_iterator,否则编译失败 - 混用
v.begin()和v.cend()可能触发隐式转换警告(尤其开启 -Wconversion) - 用
std::span(C++20)包装后传给binary_search也完全合法,只要底层数据有序
自定义类型必须提供可比性
查 struct Person?那得让 Person 支持 operator,或者传比较函数。缺一不可。
- 没定义
operator:编译报错 “no match for ‘operator- 比较逻辑和排序逻辑不一致:比如排序用年龄,查找却按姓名比,结果一定错
- lambda 比较器必须是 constexpr(C++20 起)才能用于
std::array等字面量上下文
示例:
struct Point { int x, y; };
bool operator<(const Point& a, const Point& b) { return a.x < b.x; } // 必须和 sort 用的规则一致
std::vector pts = {{1,5}, {3,2}, {7,9}};
std::sort(pts.begin(), pts.end());
bool found = std::binary_search(pts.begin(), pts.end(), Point{3,2});
实际写的时候,最容易漏掉的是排序这一步,或者误以为 binary_search 能返回索引——它连迭代器都不返,纯布尔判断。真要定位,得切到 lower_bound 那套接口。










