当前位置:   article > 正文

CPP容器vector和list,priority_queue定义比较器

CPP容器vector和list,priority_queue定义比较器
#include <iostream>
#include <bits/stdc++.h>
using  namespace  std;
struct VecCmp{
    bool operator()(int& a,int& b){
        return a>b;
        /**
         * 对于vector和list容器,这里写了>就是从大到小
         * 对于priority_queue容器,这里写了>就是从小到大!
         */
    }
};

int main(){
    vector<int> v={5,6,7,8,9,1,2,3,4};
    cout<<"Vector Element = ";
    for(auto i:v){
        cout<<i<<" ";
    }
    cout<<endl;
    sort(v.begin(),v.end(),VecCmp());
    cout<<"VecCmp Sort-----------------------------------------"<<endl;

    for(auto i:v){
        cout<<i<<" ";
    }
    cout<<endl;
    cout<<"-----------------------------------------------------"<<endl;
    list<int> l={5,6,7,8,9,1,2,3,4};
    cout<<"List Element = ";
    for(auto i:l){
        cout<<i<<" ";
    }
    l.sort();
    cout<<endl;
    cout<<"Default list sort-------------------------------------------"<<endl;
    for(auto i:l){
        cout<<i<<" ";
    }
    cout<<"\nVecCmp sort----------------------------------------------------"<<endl;
    l.sort(VecCmp());
    for(auto i:l){
        cout<<i<<" ";
    }
    cout<<endl;
    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47

在这里插入图片描述

定义了priority_queue就不一样的代码是

#include <bits/stdc++.h>
using  namespace  std;
pair<int,int> p;
class Stu{
public:
    int age;
    int grade;
    Stu(int age,int grade){
        this->age=age;
        this->grade=grade;
    }
    friend ostream& operator<<(ostream & o,const Stu& s){
        o<<"[age = "<< s.age <<", grade = "<<s.grade<<" ]";
        o<<endl;
        return  o;
    }
};
struct less1{
    bool operator()(const Stu& s1,const Stu& s2)const{
        return s1.age>s2.age;
    }
};


int main(){
    priority_queue<Stu,vector<Stu>,less1> pq;
    for(int i=0;i<10;++i){
        pq.emplace(i+18,i);
    }
    for (int i = 0; i < 10; ++i) {
        cout<<pq.top();
        pq.pop();
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

在这里插入图片描述


  • 1
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/306285
推荐阅读
相关标签
  

闽ICP备14008679号