lower_bound( first, last,val)算法返回一个非递减序列[first, last)中的第一个大于等于值val的位置
的迭代器
。
upper_bound(first, last, val)算法返回一个非递减序列[first, last)中第一个大于val的位置的迭代器。
使用头文件
#include<iostream>
using namespace std;
测试样例
#include<iostream>#include<algorithm>using namespace std;int main(){ int a[]={0,1,2,4,5,6,7,8,9,10}; //返回对应元素 cout<<*upper_bound(a,a+10,3)<<endl; //4 第一个大于 cout<<*lower_bound(a,a+10,3)<<endl; //4 第一个大于等于 //返回对应下标 cout<<upper_bound(a,a+10,4)-a<<endl; //4 第一个大于 cout<<lower_bound(a,a+10,4)-a<<endl; //3 第一个大于等于 cout<<upper_bound(a,a+10,-1)-a<<endl; //0 未找到将返回第一个 cout<<lower_bound(a,a+10,-1)-a<<endl; //0 未找到将返回第一个 cout<<upper_bound(a,a+10,11)-a<<endl; //10 未找到将返回最后 cout<<lower_bound(a,a+10,11)-a<<endl; //10 未找到将返回最后 /* 注意: 两个函数使用时,必须确定序列为非递减序列,否则会发生错误 */ return 0;}这两个函数还分别有一个重载函数,可以接受第四个参数。如果第四个参数传入greater<Type>(),其中Type改成对应类型,可以用于查找非递增序列
测试样例
#include<iostream>#include<algorithm>using namespace std;int main(){ int a[]={10,9,8,7,6,5,4,2,1,0}; cout<<upper_bound(a,a+10,4,greater<int>())-a<<endl; //7 返回第一个小于 cout<<lower_bound(a,a+10,4,greater<int>())-a<<endl; //6 返回第一个小于等于 cout<<upper_bound(a,a+10,-1,greater<int>())-a<<endl; //10 未找到将返回最后 cout<<lower_bound(a,a+10,-1,greater<int>())-a<<endl; //10 未找到将返回最后 cout<<upper_bound(a,a+10,11,greater<int>())-a<<endl; //0 未找到将返回第一个位置 cout<<lower_bound(a,a+10,11,greater<int>())-a<<endl; //0 未找到将返回第一个位置 return 0;} 两个函数配合使用可以进行查找 有序序列中的元素个数使用样例
#include<iostream>#include<algorithm>using namespace std;int main(){ int a[]={0,1,2,3,5,5,5,6,7}; //查找元素 5 的个数 cout<<upper_bound(a,a+10,5)-lower_bound(a,a+10,5)<<endl; return 0;}
新闻热点
疑难解答