upper_bound/lower_bound

函数原型

由此: 和sort类似, upper_boundlower_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));
}

其中 aa[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);
}

运行结果:

 

posted @ 2018-08-30 17:01  LizLiz  阅读(135)  评论(0)    收藏  举报