lower_bound()是在一个排好序的数组里寻找第一个大于等于查找值的数
upper_bound()是在一个排好序的数组里寻找第一个大于查找值的数
关键在于如果要找小于等于查找值的数,或者找小于查找值的数该怎么办
可以使用greater
进行修改
代码如下
#include <bits/stdc++.h>
using namespace std;
int main() {
set<int> s;
set<int, greater<int>> ss;
s.insert(1); ss.insert(1);
s.insert(3); ss.insert(3);
s.insert(5); ss.insert(5);
s.insert(7); ss.insert(7);
s.insert(9); ss.insert(9);
cout << *s.lower_bound(5) << endl; // 第一个大于等于5的值
cout << *s.upper_bound(5) << endl; // 第一个大于5的值
cout << *ss.lower_bound(5) << endl; // 第一个小于等于5的值
cout << *ss.upper_bound(5) << endl; // 第一个小于5的值
cout<<endl;
vector<int>v1;
v1.push_back(1);
v1.push_back(3);
v1.push_back(5);
v1.push_back(7);
v1.push_back(9);
//查询结果如上
cout<<*lower_bound(v1.begin(),v1.end(),5)<<endl;
cout<<*upper_bound(v1.begin(),v1.end(),5)<<endl;
reverse(v1.begin(),v1.end());
//如果是数组或者vector的话,寻找小于等于或者小于,需要将其从大到小排序
cout<<*lower_bound(v1.begin(),v1.end(),5,greater<int>())<<endl;
cout<<*upper_bound(v1.begin(),v1.end(),5,greater<int>())<<endl;
}