lower_bound 和upper_bound 用法简介
lower_bound( )和upper_bound( )都是利用二分查找的方法在一个排好序的数组中进行查找的。
函数原型
lower_bound(_ForwardIterator __first, _ForwardIterator __last,const _Tp& __val)
upper_bound(_ForwardIterator __first, _ForwardIterator __last,const _Tp& __val)
lower_bound(_ForwardIterator __first, _ForwardIterator __last,const _Tp& __val, _Compare __comp)
upper_bound(_ForwardIterator __first, _ForwardIterator __last,const _Tp& __val, _Compare __comp)
函数作用
当数组元素从小到大排序时:
lower_bound(first, last, val): 利用二分法 查找 从地址 first 到地址 last 中第一个大于等于val的值 返回元素地址
upper_bound(first, last, val): 利用二分法 查找 从地址 first 到地址 last 中第一个大于val的值 返回元素地址
当数组元素从大到小排序,或者元素无法直接比较时:
类似sort(),需要加一个cmp函数,把比较规则告诉计算机。
lower_bound(first, last, val, cmp)
upper_bound(first, last, val, cmp)
返回的地址 - 数组名 可以将结果转换成数组下标
示例代码
当数组元素从小到大排序
//从小到大排序的数字 进行二分查找
#include <bits/stdc++.h>
using namespace std;
int main( )
{
int a[10]={0,1,2,3,4,5},index;
index = lower_bound(a,a+5,6)-a; //输出 5 没找到 结果是last
index = lower_bound(a,a+5,-1)-a; //输出 0
index = lower_bound(a,a+5,3)-a; //输出 3
index = upper_bound(a,a+5,5)-a; //输出 5 没找到 结果是last
index = upper_bound(a,a+5,-1)-a; //输出 0
index = upper_bound(a,a+5,3)-a; //输出 4
cout<<index;
return 0;
}
当数组元素从大到小排序 进行二分查找 这时任务是找第一个小于等于或者小于 x 的 元素的地址
//从大到小排序的组 这时任务是找第一个小于等于或者小于 x 的 元素的地址
#include <bits/stdc++.h>
using namespace std;
bool cmp(int a,int b)
{
return a > b;
}
int main( )
{
int a[10]={5,4,3,2,1,0},index;
index = lower_bound(a,a+5,6,cmp)-a; //输出 0
index = lower_bound(a,a+5,-1,cmp)-a; //输出 5 没找到 结果是 地址 last
index = upper_bound(a,a+5,4,cmp)-a; //输出 2
index = upper_bound(a,a+5,-1,cmp)-a; //输出 0
cout<<index;
return 0;
}
当数组元素是没办法直接比较的数据类型时:
//结构体 进行二分查找
/*
测试数据:
4
0 0
1 1
2 2
3 3
*/
#include <bits/stdc++.h>
using namespace std;
struct bs {
int a;
int b;
} x[2000];
bool cmp(bs x,bs y) {
return x.a < y.a;
}
int main( )
{
int n,index;
scanf("%d",&n);
for(int i=1; i<=n; i++)
cin>>x[i].a>>x[i].b;//读入数据
bs tmp = {2,2};
index = lower_bound(x,x+5,tmp,cmp)-x; //输出 3
cout<<index;
return 0;
}
其他STL的用法:
原文链接:https://blog.csdn.net/NEFU_kadia/article/details/104435627
vector<int>v;
v.push_back(1);
v.push_back(3);
v.push_back(2);
v.push_back(5);
v.push_back(7);
sort(v.begin(),v.end());// 1 2 3 5 7
int t;
t=upper_bound(v.begin(),v.end(),4)-v.begin();
// 第一个大于4的迭送器与容器中第一个数的迭送器做差
cout << t << endl ; // 输出 3
cout << v[t] << endl ; // 输出 5
set<int>s;
s.insert(1);
s.insert(3);
s.insert(5);
s.insert(7);
s.insert(9);
set<int>::iterator it;//定义迭送器
int x=6;
it=upper_bound(s.begin(),s.end(),x); //查找第一个大于x的元素的迭送器
cout << *it << endl ; //输出迭送器所对应的值 7
set对我们挺友好的,它直接向我们提供了在它整个set里寻找此类x的函数。所以如果我们是在整个set里查找的话,可以直接这样写:
set<int>s;
s.insert(1);
s.insert(3);
s.insert(5);
s.insert(7);
s.insert(9);
set<int>::iterator it;//定义迭送器
int x=6;
it=s.upper_bound(x); //查找第一个大于x的元素的迭送器
cout << *it << endl ; //输出迭送器所对应的值 7