前提 数据有序!
升序
upper_bound( first , last , value )
返回指向范围 [first, last) 中首个大于 value 的元素的迭代器,若找不到则返回 last 。
lower_bound( first , last , value )
返回指向范围 [first, last) 中首个大于等于 value 的元素的迭代器,若找不到则返回 last 。
降序
upper_bound( first , last , value , greater<type>() )
返回指向范围 [first, last) 中首个小于 value 的元素的迭代器,若找不到则返回 last 。
lower_bound( first , last , value , greater<type>() )
返回指向范围 [first, last) 中首个小于等于 value 的元素的迭代器,若找不到则返回 last 。
数组
const int n=10;
int a[n+10];
for(int i=0;i<n;i++)
a[i]=i;
cout<<upper_bound(a,a+n,2)-a<<" "<<*upper_bound(a,a+n,2)<<endl;
//输出大于2的位置和值
// 3 3
cout<<lower_bound(a,a+n,2)-a<<" "<<*lower_bound(a,a+n,2);
//输出大于等于2的位置和值
// 2 2
vector
const int n=10;
vector<int>s;
vector<int>::iterator it1,it2,it;
for(int i=0;i<n;i++)
s.push_back(i);
it1=lower_bound(s.begin(),s.end(),3);
//int idx=lower_bound(s.begin(),s.end(),3)-s.begin(); //位置
it2=upper_bound(s.begin(),s.end(),6);
cout<<*it1<<" "<<*it2<<endl;
//输出大于等于3的值和大于6的值
s.erase(it1,it2);// 删除区间内的元素,区间左闭右开
for(it=s.begin();it!=s.end();++it)
cout<<*it<<" ";
/*
3 7
0 1 2 7 8 9
*/