C++ sort()对结构体排序

☆樱花仙子☆ 提交于 2020-03-02 12:58:39

重写仿函数(函数指针法)

#include<iostream>
#include<algorithm>
using namespace std;

struct stu{
    int num;
    float score;
}; 

bool cmp(const stu &a, const stu &b){
    return a.score < b.score;
}

int main(){
    stu nums[3] = {{1,98.5}, {2,88.5}, {3,68.5}};
    sort(nums, nums + 3, cmp);
    for(int i = 0; i < 3; ++ i)
    {
        cout << nums[i].score <<endl;
    }
    return 0;
}

重载运算符(struct内部 + struct外部)

#include<iostream>
#include<algorithm>
using namespace std;

struct stu{
    int num;
    float score;
    bool operator<(const stu &a) const
    {
        return score < a.score;
    }
}; 

int main(){
    stu nums[3] = {{1,98.5}, {2,88.5}, {3,68.5}};
    sort(nums, nums + 3);
    for(int i = 0; i < 3; ++ i)
    {
        cout << nums[i].score <<endl;
    }
    return 0;
}
#include<iostream>
#include<algorithm>
using namespace std;

struct stu{
    int num;
    float score;
}; 

bool operator<(const stu &a, const stu &b)
{
    return a.score < b.score;
}

int main(){
    stu nums[3] = {{1,98.5}, {2,88.5}, {3,68.5}};
    sort(nums, nums + 3);
    for(int i = 0; i < 3; ++ i)
    {
        cout << nums[i].score <<endl;
    }
    return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!