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 未找到將返回最后 /* 注意: 兩個函數(shù)使用時,必須確定序列為非遞減序列,否則會發(fā)生錯誤 */ return 0;} 這兩個函數(shù)還分別有一個重載函數(shù),可以接受第四個參數(shù)。如果第四個參數(shù)傳入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;} 兩個函數(shù)配合使用可以進行查找 有序序列中的元素個數(shù)使用樣例
#include<iostream>#include<algorithm>using namespace std;int main(){ int a[]={0,1,2,3,5,5,5,6,7}; //查找元素 5 的個數(shù) cout<<upper_bound(a,a+10,5)-lower_bound(a,a+10,5)<<endl; return 0;}
新聞熱點
疑難解答