lower_bound自定义比较函数
时间: 2025-04-06 14:10:13 AIGC 浏览: 77
### 如何在 C++ `lower_bound` 中使用自定义比较函数
#### 自定义比较函数的作用
当调用 `std::lower_bound` 时,默认情况下它会假设输入序列按照升序排列,并基于小于运算符 `<` 来执行二分查找操作。然而,如果需要改变默认的行为(例如处理降序数组或者更复杂的排序逻辑),可以通过传递一个自定义的比较函数来实现特定的需求。
#### 实现方式
为了使 `lower_bound` 支持自定义比较规则,可以向该函数传入第三个参数——即用户定义的谓词 (predicate),这个谓词接受两个参数并返回布尔值。具体来说:
- 如果希望按降序顺序工作,则需重新定义“较小”的概念;
- 或者对于某些复杂数据结构对象之间的对比关系也需要通过这种方式指定。
下面给出几个具体的例子说明如何做到这一点。
#### 示例代码展示
##### 示例 1: 对于整数类型的降序数组应用 lower_bound 并带有一个简单的 lambda 表达式作为定制化条件。
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
int main(){
std::vector<int> v = {9,7,5,3,1}; // A descending sorted vector
auto it = std::lower_bound(v.begin(),v.end(),4,
[](const int& a,const int& b)->bool{return a>b;}
);
if(it != v.end()){
std::cout << *it;
}else{
std::cout << "Not Found";
}
}
```
上述程序片段展示了如何利用 Lambda 表达式创建一个新的比较准则以便适应已知为递减次序的数据集合情况下的搜索需求[^2]。
##### 示例 2: 面向类实例成员变量进行比较的情况
假设有如下 Student 类型表示学生姓名及其成绩的信息单元格;现在我们想要找到第一个分数不低于某个阈值的学生记录位置。
```cpp
struct Student {
string name;
double score;
bool operator<(const Student &other)const{
return this->score<other.score;// 默认从小到大排
}
};
//...
vector<Student> students={{"Alice",80},{"Bob",75},{"Charlie",60}};
double threshold=70;
auto cmp=[threshold](const Student&s){return s.score<threshold;};
auto pos=find_if(students.cbegin(),students.cend(),not1(std::bind(cmp,_1)));
if(pos!=students.cend())
cout<<pos->name<<" has at least "<<threshold<<" points.";
else
cout<<"No one achieved more than or equal to "<<threshold<<" points.";
```
这里采用了绑定技术结合 not1 转换器构造出了适配 find_if 的形式化表达式[^3]。
#### 总结
无论是基本数值还是复合类型都可以借助额外提供的 predicate 参数来自由调整匹配策略从而满足实际应用场景的要求。值得注意的是,在设计这些辅助判断依据的时候一定要注意保持一致性原则以免引发不可预期的结果。
阅读全文
相关推荐



















