列举三种自定义排序比较规则

这篇博客探讨了在STL中如何为自定义类型实现排序。通过介绍三种不同的方法,包括使用自定义函数、重载比较运算符以及编写仿函数,详细阐述了如何为自定义数据类型设置排序规则,确保它们能在sort函数中正确排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在STL中,有一个sort函数,可以对int,double等类型进行排序,而对于一些用户自定义的类型而无法排序,是因为它(函数)不知道如何对自定义数据进行比较,这时候就需要用户自己编写比较规则了。
列举三种常见的比较规则写法。

① 自定义函数

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
struct Goods
{
	string name;
	double price;
};
bool Compare(const Goods g1, const Goods g2)自定义
{
	return g1.price>g2.price;
}
int main()
{
	Goods gd[] = { { "苹果", 3.14 }, { "香蕉", 2.5 }, {"橘子",2.8} };
	int n = sizeof(gd) / sizeof(gd[0]);
	sort(gd,gd+n,Compare);利用Compare函数
	for (const auto &e : gd)
		cout << e.name << ":" << e.price << endl;
	return 0;
}

② 重载比较符(> <)

#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
using namespace std;
struct Goods
{
	string name;
	double price;
	bool operator<(const Goods g)const 
	{
		return price < g.price;
	}
};
int main()
{
	Goods gd[] = { { "苹果", 3.14 }, { "香蕉", 2.5 }, {"橘子",2.8} };
	int n = sizeof(gd) / sizeof(gd[0]);
	sort(gd,gd+n,less<Goods>());  利用系统的仿函数,自定义比较规则
	for (const auto &e : gd)
		cout << e.name << ":" << e.price << endl;
	return 0;
}

③ 自己编写仿函数

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
struct Goods
{
	string name;
	double price;
};
struct Less自己模拟实现仿函数
{
	bool operator()(const Goods g1, const Goods g2)重载括号
	{
		return g1.price < g2.price;
	}
};
int main()
{
	Goods gd[] = { { "苹果", 3.14 }, { "香蕉", 2.5 }, {"橘子",2.8} };
	int n = sizeof(gd) / sizeof(gd[0]);
	sort(gd,gd+n,Less<Goods>());
	for (const auto &e : gd)
		cout << e.name << ":" << e.price << endl;
	return 0;
}

三种结果都一样,结果如下
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值