C/C++教程

C++-sort对结构体排序

本文主要是介绍C++-sort对结构体排序,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

原文链接:https://www.cnblogs.com/xiaobaizzz/p/12394951.html

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

include

include

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

include

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

include

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;
}

这篇关于C++-sort对结构体排序的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!