日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

c++自定義sort()函數的排序方法介紹_C 語言

作者:愛鉆研的小銘 ? 更新時間: 2022-11-12 編程語言

1. 引言

在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按照指定規則排列。這種方法可以對多個維度排序,更靈活
  • 仿函數:寫仿函數cmp,傳入cmp<Type>()按照指定規則排列。這種方法可以對多個維度排序,更靈活。

2. 自定義排序規則

2.1 重寫 < 或 > 運算符

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

2.2 普通函數

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

2.3 仿函數

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

原文鏈接:https://blog.csdn.net/qq_42676511/article/details/126955901

欄目分類
最近更新