在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;
}
三种结果都一样,结果如下