zoukankan      html  css  js  c++  java
  • STL_lower_bound&upper_bound用法

    ForwardIter lower_bound(ForwardIter first, ForwardIter last,const _Tp& val)算法返回一个非递减序列[first, last)中的第一个大于等于值val的位置。

         ForwardIter upper_bound(ForwardIter first, ForwardIter last, const _Tp& val)算法返回一个非递减序列[first, last)中第一个大于val的位置。

    下面是这两个功能的实现:

     1 #include <iostream>
     2 #include <cstdio>
     3 
     4 using namespace std;
     5 
     6 int my_lower_bound(int array[],int len,int t){
     7     int s=0,e=len-1;
     8     int mid;
     9     int ans;
    10     while(s<e){
    11         mid=(s+e)/2;
    12         if(array[mid]>=t){
    13             e=mid;
    14             ans=e;
    15         }else{
    16             s=s+1;;
    17             ans=s;
    18         }
    19     }
    20     return ans;
    21 }
    22 
    23 int my_upper_bound(int array[],int len,int t){
    24     int s=0,e=len-1;
    25     int mid;
    26     int ans;
    27     while(s<e){
    28         mid=(s+e)/2;
    29         if(array[mid]<=t){
    30             s+=1;
    31             ans=s;
    32         }else{
    33             e=mid;
    34             ans=e;
    35         }
    36     }
    37     return ans;
    38 }
    39 
    40 int main()
    41 {
    42     int a[10]={1,2,2,3,4,4,4,4,5,6};
    43     int l=my_lower_bound(a,10,4);//数值4
    44     int u=my_upper_bound(a,10,4);//数值5
    45     printf("%d %d",a[l],a[u]);
    46     return 0;
    47 }
  • 相关阅读:
    题目1101:计算表达式
    九度oj 题目1107:搬水果
    [Hihocoder] 字符串排序
    [hzwer] 模拟T
    [Luogu] 宝藏
    [Luogu] 列队
    [Luogu] 奶酪
    [Luogu] 逛公园
    [Luogu] 时间复杂度
    [Luogu] 小凯的疑惑
  • 原文地址:https://www.cnblogs.com/TWS-YIFEI/p/5990976.html
Copyright © 2011-2022 走看看