c++排序 sort()、priority_queue优先队列(注意队列只能在尾部拿到元素,这就导致看到的顺序与实际顺序相反)

1.sort算法排序

 sort(起始地址,结束地址)基本的数据类型从小到大排序

以int数据类型为例:

vector<int> v = {2,1,4,5,3};

 sort(v.begin(), v.end());

输出结果为

PS C:\Users\17635> cd "c:\Users\17635\Desktop\kbfvictory\c++练习\" ; if ($?) { g++ kbf.cpp -o kbf } ; if ($?) { .\kbf }
1
2
3
4
5
也可以使用sort(v.begin(), v.end(), less<int>())这种方式实现。

从大到小可以使用sort(ve.begin(), v.end(), greater<int>())这种方式实现。

自定义数据类型排序,可以写个bool函数实现,如下:

struct Person{
    Person(int age, string name):m_age(age),m_name(name){};
    string m_name;
    int m_age;
};

bool cmp(Person a, Person b){
    return a.m_age > b.m_age;
}

int main(){
    Person p1(2, "a"), p2(1, "b"), p3(3, "c");
    
    vector<Person> v = {p1,p2,p3};
    for(auto ch : v){
        cout << ch.m_age << endl;
    }
    sort(v.begin(), v.end(), cmp);
     for(auto ch : v){
        cout << ch.m_age << endl;
    }

    
 
    return 0;
}

输出结果如下:

尝试新的跨平台 PowerShell https://aka.ms/pscore6

PS C:\Users\17635> cd "c:\Users\17635\Desktop\kbfvictory\c++练习\" ; if ($?) { g++ kbf.cpp -o kbf } ; if ($?) { .\kbf }
2
1
3
3
2
1
PS C:\Users\17635\Desktop\kbfvictory\c++练习> 

bool函数里面当第一个参数大于第二个参数为从大到小排序;反之,当第一个参数小于第二个参数时为从小到大排序。

2.priority_queue排序

当我们需要用有限队列priority_queue对自定义数据类型进行排序时需要传入三个数据类型来构建对象 priority_queue<排序对象的数据类型, vector<排序对象的数据类型>, 重载()的自定义数据类型(里面包含重载())>, 如下:

#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<queue>
using namespace std;
struct Person{
    Person(int age, string name):m_age(age),m_name(name){};
    string m_name;
    int m_age;
};
struct cmp
{
    bool operator()(Person a, Person b){
    return a.m_age < b.m_age;
}
};



int main(){
    // Person p1(2, "a"), p2(1, "b"), p3(3, "c");
    
    // priority_queue<Person, vector<Person>, cmp> q;
    // q.push(p1);
    // q.push(p2);
    // q.push(p3);
   
    
    // for(int i = 0; i < 3; i++){
    //     cout << q.top().m_age << endl;
    //     q.pop();
    // }
    priority_queue<int, vector<int>> q;
    q.push(2);
    q.push(1);
    q.push(3);
    int a = q.size();
    cout << a << endl;
    for(int i = 0; i< a; i++){
        cout << q.top() << endl;
        q.pop();
    }
    return 0;
}

结果如下:

尝试新的跨平台 PowerShell https://aka.ms/pscore6

PS C:\Users\17635> cd "c:\Users\17635\Desktop\kbfvictory\c++练习\" ; if ($?) { g++ kbf.cpp -o kbf } ; if ($?) { .\kbf }
3
3
2
1
PS C:\Users\17635\Desktop\kbfvictory\c++练习> 

当排序的数据类型为基本数据类型时,第三个数据类型可不写,默认从小到大排序(注意:由于时对列,头只能进入数据而为尾部是出数据,所有如果以出对的顺序来访问元素的话,会从大到小显示,刚好与我们排序相反,因为我们是从队尾开始访问数据

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值