zoukankan      html  css  js  c++  java
  • STL中的unique()和lower_bound ,upper_bound

    unique():

    作用:unique()的作用是去掉容器中相邻元素的重复元素(数组可以是无序的,比如数组可以不是按从小到大或者从大到小的排列方式)

    使用方法:unique(初始地址,末地址);

    注意:

    1.unique()函数返回值不是去重后容器中元素的数量,而是去重后容器中的末地址。也就是说,如果想得到去重后容器中元素的数量的话还要减去初始地址。

    2.unique函数在去重的时候不会扔掉重复元素,而是会把它放在容器的末尾,也就是说数组的长度一直没有变化

    #include<bits/stdc++.h>
    using namespace std;
    #define forn(i,n) for(int i=0;i<n;i++)
    bool cmp(int a,int b){
        return a>b;
    }
    int main()
    {
        int n;cin>>n;
        int a[n+5];
        forn(i,n)cin>>a[i];
    
        sort(a,a+n,cmp);
        forn(i,n)cout<<a[i];cout<<endl;
    
        int m=unique(a,a+n)-a;
        cout<<m<<endl;
        return 0;
    }

     lower_bound,upper_bound

    lower_bound( )和upper_bound( )都是利用二分查找的方法在一个排好序的数组中进行查找的。

    lower_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于或等于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。

    upper_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。

    #include<iostream>
    #include<algorithm>
    using namespace std;
    int a[5]={1,2,3,4,5};
    int main(){
        sort(a,a+5);
        int t1=lower_bound(a,a+5,3)-a;
        int t2=upper_bound(a,a+5,3)-a;
        cout<<t1<<endl;///返回的是地址
        cout<<t2<<endl;
        return 0; 
    }
    /*
    2
    3
    */
  • 相关阅读:
    从头学pytorch(二十一):全连接网络dense net
    Linux环境实现python远程可视编程
    centos7安装Anaconda3
    sql语句中包含引号处理方法
    syslog 日志
    python 判断是否为中文
    numpy简介
    django之模板显示静态文件
    Linux(Ubuntu)安装libpcap
    Bug预防体系
  • 原文地址:https://www.cnblogs.com/angelliu/p/13032128.html
Copyright © 2011-2022 走看看