• 【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;
    }
    祝你早日攒够失望,然后开始新的生活。
  • 相关阅读:
    P1613 跑路
    数据挖掘-聚类分析(Python实现K-Means算法)
    使用scikit-learn 估计器分类
    数据挖掘-集成学习
    数据挖掘-关联分析 Apriori算法和FP-growth 算法
    scikit-learn 中常用的评估模型
    数据挖掘---支持向量机(SVM)
    数据挖掘-KNN-K最近邻算法
    数据挖掘-决策树
    数据挖掘-逻辑Logistic回归
  • 原文地址:https://www.cnblogs.com/LuRenJiang/p/7237460.html
Copyright © 2020-2023  润新知