【STL学习】upper_bound()和lower_bound()

1)ForwardIterator upper_bound (ForwardIterator first, ForwardIterator last, const T& val);

指向[first , last)中第一个>val的元素;

2)ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last, const T& val);

指向[first , last)中第一个>=val的元素

注意:

在使用时,需要保证[begin , end)中元素已经有序

②是在左闭右开的区间内。

③不适用于普通数组。

④在查找大于或大于等于val的那个元素时,采用的是二分查找

 

代码测试:

 

#include <iostream>
#include <vector>
#include <stdio.h>
#include <algorithm>
using namespace std;

int main()
{
    int aim=8;//要找的数

    //用数组初始化容器
    int a[]={4,5,6,3,7,8,2,1,9,0};
    size_t cnt=sizeof(a)/sizeof(int);
    vector<int> v(a,a+cnt);
    //用迭代器遍历元素
    vector<int>::iterator it,location,start,end;
    start=v.begin();
    end=v.end();

    sort(start,end);
    printf("对v里的元素排序:\n");
    for(it=start;it!=end;it++){
        printf("%d ",*it);
    }

    printf("\nupper_bound测试:");
    location=upper_bound(start,end,aim);
    printf("aim=8,upper_bound()找的位置是大于aim的位置,所以找到的位置为:%d\n",location-start);

    printf("lower_bound测试:");
    location=lower_bound(start,end,aim);
    printf("aim=8,lower_bound()找的位置是大于等于aim的位置,所以找到的位置为:%d\n",location-start);

    //下面有两个有点不同的情况
     aim=10;

    location=upper_bound(start,end,aim);
    printf("aim=10,upper_bound()此时第二个参数是指向最后一个元素,在这种情况下,是大于第二个参数的指针,找到的位置是第二个参数的位置的后一个:%d\n",location-start);
    //个人认为和第二个参数是不是指向最后一个元素的指针有关,我对这个函数理解的还是不彻底,希望明白的大佬给解释下为啥下面这种情况没有指向aim位置的后一个???
    location=upper_bound(start,start+8,aim);
    printf("aim=10,upper_bound()此时第二个参数是指向8的,在这种情况下,返回的值并不是大于第二个参数的指针,找到的位置和第二个参数的位置相同为:%d\n",location-start);
    return 0;
}

 

posted @ 2017-07-26 08:38  路人姜。  阅读(201)  评论(0编辑  收藏  举报