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