• lower_bound upper_bound


    这两个函数针对有序数列进行二分查找

    lower_bound返回第一个大于等于 x 的元素的位置的迭代器(或指针)

    upper_bound返回第一个大于 x 的元素的位置的迭代器(或指针)

    若序列从大到小排列 则可以分别求得 第一个小于等于 x 的元素位置 和 第一个小于x 的元素位置

    根据习惯从1记录数组

     1 #include<iostream>
     2 #include<algorithm>
     3 #include<cstdio>
     4 using namespace std;
     5 int a[200];
     6 int n,k;
     7 bool cmp(int a,int b){return a>b;}
     8 int main()
     9 {
    10     scanf("%d",&n);
    11     for(int i=1;i<=n;i++)
    12         scanf("%d",&a[i]);
    13     scanf("%d",&k);
    14     int pos1=lower_bound(a+1,a+n+1,k)-a;
    15     int pos2=upper_bound(a+1,a+n+1,k)-a;
    16     cout<<pos1<<" "<<a[pos1]<<endl;
    17     cout<<pos2<<" "<<a[pos2]<<endl;
    18     sort(a+1,a+n+1,cmp);
    19     for(int i=1;i<=n;i++) cout<<a[i]<<" ";
    20     cout<<endl;
    21     pos1=lower_bound(a+1,a+n+1,k,greater<int>())-a;
    22     pos2=upper_bound(a+1,a+n+1,k,greater<int>())-a;
    23     cout<<pos1<<" "<<a[pos1]<<endl;
    24     cout<<pos2<<" "<<a[pos2]<<endl;
    25     return 0;
    26 }
    27 /*
    28 7
    29 2 3 4 8 9 10 12
    30 4
    31 */
  • 相关阅读:
    函数传参总结
    集合操作总结
    深浅拷贝总结
    三级列表展示
    文件操作总结
    vue-router之嵌套路由
    vue-router之动态路由
    Sublime编辑VUE实现代码高亮
    Windows系统下Vue开发环境搭建详解版
    C#调用快递鸟电子面单API实现批量打印电子面单功能
  • 原文地址:https://www.cnblogs.com/kylara/p/9922949.html
Copyright © 2020-2023  润新知