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

cpp 复制代码
#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;
}

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

cpp 复制代码
#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();
    }
}
复制代码
相关推荐
凯子坚持 c2 天前
精通 Redis list:使用 redis-plus-plus 的现代 C++ 实践深度解析
c++·redis·list
第七序章2 天前
【C++STL】list的详细用法和底层实现
c语言·c++·自然语言处理·list
摇滚侠3 天前
java语言中,list<String>转成字符串,逗号分割;List<Integer>转字符串,逗号分割
java·windows·list
我星期八休息3 天前
深入理解跳表(Skip List):原理、实现与应用
开发语言·数据结构·人工智能·python·算法·list
掘根3 天前
【CMake】List
windows·microsoft·list
恣艺4 天前
Redis列表(List):实现队列/栈的利器,底层原理与实战
数据库·redis·list
一枝小雨4 天前
【C++】list 容器操作
开发语言·c++·笔记·list·学习笔记
小六子成长记4 天前
【C++】:list容器全面解析(超详细)
c++·windows·list
重生之我是Java开发战士5 天前
【数据结构】Java集合框架:List与ArrayList
java·数据结构·list
minji...5 天前
C++ list的模拟实现
开发语言·c++·list