目录1. 引言2. 自定义排序规则2.1 重写 < 或 > 运算符2.2 普通函数2.3 仿函数1. 引言 在c++中,sort()函数常常用来对容器内的元素进行排序,先
在c++中,sort()函数常常用来对容器内的元素进行排序,先来了解一下sort()函数。
sort()函数有三个参数:
less<Type>()
,还提供了greater<Type>()
进行从大到小排序。这个参数的类型是函数指针
,less和greater
实际上都是类/结构体
,内部分别重载了()运算符
,称为仿函数,所以实际上less<Type>()和greater<Type>()
都是函数名,也就是函数指针。我们还可以用普通函数来定义排序方法。如果容器内元素的类型是内置类型或string类型
,我们可以直接用less<Type>()或greater<Type>()
进行排序。但是如果数据类型是我们自定义的结构体或者类的话,我们需要自定义排序函数,
有三种写法:
<
运算符,传入less<Type>()
进行升序排列。重载 >
运算符,传入greater<Type>()
进行降序排列。这种方法只能针对一个维度排序,不灵活。cmp
按照指定规则排列。这种方法可以对多个维度排序,更灵活。cmp<Type>()
按照指定规则排列。这种方法可以对多个维度排序,更灵活。#include <bits/stdc++.h>
using namespace std;
struct Person {
int id;
int age;
Person(int id,int age):id(id),age(age){}
//重载<运算符,进行升序排列
bool operator < (const Person& p2) const {
return id < p2.id;
}
//重载>运算符,进行降序排列
bool operator > (const Person& p2) const {
return id > p2.id;
}
};
int main()
{
Person p1(1, 10), p2(2, 20), p3(3, 30);
vector<Person> ps;
ps.push_back(p2);
ps.push_back(p1);
ps.push_back(p3);
sort(ps.begin(), ps.end(), less<Person>());
for (int i = 0; i < 3; i++) {
cout << ps[i].id << " " << ps[i].age << endl;
}
cout << endl;
sort(ps.begin(), ps.end(), greater<Person>());
for (int i = 0; i < 3; i++) {
cout << ps[i].id << " " << ps[i].age << endl;
}
cout << endl;
}
#include <bits/stdc++.h>
using namespace std;
struct Person {
int id;
int age;
Person(int id,int age):id(id),age(age){}
};
//普通函数
bool cmp(const Person& p1, const Person& p2) {
if (p1.id == p2.id) return p1.age >= p2.age;
return p1.id < p2.id;
}
int main()
{
Person p1(1, 10), p2(2, 20), p3(3, 30), p4(3, 40);
vector<Person> ps;
ps.push_back(p2);
ps.push_back(p1);
ps.push_back(p3);
ps.push_back(p4);
sort(ps.begin(), ps.end(), cmp);//传入函数指针cmp
for (int i = 0; i < 4; i++) {
cout << ps[i].id << " " << ps[i].age << endl;
}
}
#include <bits/stdc++.h>
using namespace std;
struct Person {
int id;
int age;
Person(int id, int age) :id(id), age(age) {}
};
//仿函数
struct cmp {
bool operator()(const Person& p1, const Person& p2) {
if (p1.id == p2.id) return p1.age >= p2.age;
return p1.id < p2.id;
}
};
int main()
{
Person p1(1, 10), p2(2, 20), p3(3, 30), p4(3, 40);
vector<Person> ps;
ps.push_back(p2);
ps.push_back(p1);
ps.push_back(p3);
ps.push_back(p4);
sort(ps.begin(), ps.end(), cmp()); //传入函数指针cmp()
for (int i = 0; i < 4; i++) {
cout << ps[i].id << " " << ps[i].age << endl;
}
}
到此这篇关于c++自定义sort()函数的排序方法介绍的文章就介绍到这了,更多相关c++ sort排序内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: c++自定义sort()函数的排序方法介绍
本文链接: https://www.lsjlt.com/news/168083.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0