upper_bound/lower_bound
函数原型

由此: 和sort类似, upper_bound和lower_bound可选择自带比较函数, 也可以不带。
作用: lower_bound为返回数组中查找的元素第一次出现的位置。
upper_bound为返回数组中查找的元素最后一次出现的位置的下一个位置。
若数组已经排序, 则复杂度为O(logn)
否则为O(n)
举例
#include<bits/stdc++.h> using namespace std; int main() { int a[]={0,0,0,1,1,1,2,2,2,3,3,3}; printf("%d\n%d\n",*upper_bound(a,a+12,1),*lower_bound(a,a+12,1)); }
其中 a为a[0]元素的地址。
a+12,为a中最后一个元素a[11]的下一个位置的地址。
所以, 输出结果为:
运行结果:

#include<bits/stdc++.h> using namespace std; int main() { int a[]={0,0,0,1,1,1,2,2,2,3,3,3}; printf("%d\n%d\n",upper_bound(a,a+12,1)-a,lower_bound(a,a+12,1)-a); }
运行结果:


浙公网安备 33010602011771号