zoukankan      html  css  js  c++  java
  • 【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里的元素排序:
    ");
        for(it=start;it!=end;it++){
            printf("%d ",*it);
        }
    
        printf("
    upper_bound测试:");
        location=upper_bound(start,end,aim);
        printf("aim=8,upper_bound()找的位置是大于aim的位置,所以找到的位置为:%d
    ",location-start);
    
        printf("lower_bound测试:");
        location=lower_bound(start,end,aim);
        printf("aim=8,lower_bound()找的位置是大于等于aim的位置,所以找到的位置为:%d
    ",location-start);
    
        //下面有两个有点不同的情况
         aim=10;
    
        location=upper_bound(start,end,aim);
        printf("aim=10,upper_bound()此时第二个参数是指向最后一个元素,在这种情况下,是大于第二个参数的指针,找到的位置是第二个参数的位置的后一个:%d
    ",location-start);
        //个人认为和第二个参数是不是指向最后一个元素的指针有关,我对这个函数理解的还是不彻底,希望明白的大佬给解释下为啥下面这种情况没有指向aim位置的后一个???
        location=upper_bound(start,start+8,aim);
        printf("aim=10,upper_bound()此时第二个参数是指向8的,在这种情况下,返回的值并不是大于第二个参数的指针,找到的位置和第二个参数的位置相同为:%d
    ",location-start);
        return 0;
    }
    祝你早日攒够失望,然后开始新的生活。
  • 相关阅读:
    Java基础知识 String StringBuffer StringBuilder三者的区别(面试题)
    周学习笔记(10)——大三下
    中国软件杯——基于计算机视觉的交通场景智能应用
    unable to find Qt5Core.dll on PATH(已解决,超简单)
    周学习笔记(09)——大三下
    《一线架构师实践指南》阅读笔记三
    周学习笔记(08)——大三下
    《一线架构师实践指南》阅读笔记二
    周学习笔记(07)——大三下
    《一线架构师实践指南》阅读笔记一
  • 原文地址:https://www.cnblogs.com/LuRenJiang/p/7237460.html
Copyright © 2011-2022 走看看