这两个函数使用前提是,容器内元素是有序的。
lower_bound
- Returns an iterator pointing to the first element that is not less than key.
- Returns an iterator pointing to the first element that compares not less to the value x. This overload only participates in overload resolution if the qualified-id Compare::is_transparent is valid and denotes a type. They allow calling this function without constructing an instance of Key.
Return value
Iterator pointing to the first element that is not less than key. If no such element is found, a past-the-end iterator (see end()) is returned.
模版:
lower_bound(vec.begin(),vec.end(),x);
//返回第一个不小于x的迭代器
lower_bound(vec.begin(),vec.end(),x)-vec;
//返回第一个不小于x的下标
如果没有则返回end()
int a[10] = {2,3,4,5,6,7,8,9,10,11};
int s = lower_bound(a,a+10,4)-a;
cout<<s<<endl; //返回下标2,因为4的下标为2
auto *it = lower_bound(a,a+10,5);
cout<<*it<<endl; //返回值5
upper_bound
- Returns an iterator pointing to the first element that is greater than key.
- Returns an iterator pointing to the first element that compares greater to the value x. This overload only participates in overload resolution if the qualified-id Compare::is_transparent is valid and denotes a type. They allow calling this function without constructing an instance of Key.
Return value
Iterator pointing to the first element that is greater than key. If no such element is found, past-the-end (see end()) iterator is returned.
模版
upper_bound(vec.begin(),vec.end(),x);
//返回第一个大于x的迭代器
upper_bound(vec.begin(),vec.end(),x)-vec;
//返回第一个大于x的元素的下标
int a[10] = {2,3,4,5,6,7,8,9,10,11};
int s = upper_bound(a,a+10,4)-a;
cout<<s<<endl; //返回下标3,因为5是第一个大于4的元素
auto *it = upper_bound(a,a+10,5);
cout<<*it<<endl;//返回值6,因为6是第一个大于5的元素