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

學(xué)無先后,達者為師

網(wǎng)站首頁 編程語言 正文

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

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

1. 引言

在C++中,sort()函數(shù)常常用來對容器內(nèi)的元素進行排序,先來了解一下sort()函數(shù)。

sort()函數(shù)有三個參數(shù):

  • 第一個是要排序的容器的起始迭代器
  • 第二個是要排序的容器的結(jié)束迭代器
  • 第三個參數(shù)是排序的方法,是可選的參數(shù)。默認的排序方法是從小到大排序,也就是less<Type>(),還提供了greater<Type>()進行從大到小排序。這個參數(shù)的類型是函數(shù)指針less和greater實際上都是類/結(jié)構(gòu)體,內(nèi)部分別重載了()運算符,稱為仿函數(shù),所以實際上less<Type>()和greater<Type>()都是函數(shù)名,也就是函數(shù)指針。我們還可以用普通函數(shù)來定義排序方法。

如果容器內(nèi)元素的類型是內(nèi)置類型或string類型,我們可以直接用less<Type>()或greater<Type>()進行排序。但是如果數(shù)據(jù)類型是我們自定義的結(jié)構(gòu)體或者類的話,我們需要自定義排序函數(shù),

有三種寫法:

  • 重載 < 或 > 運算符:重載 < 運算符,傳入less<Type>()進行升序排列。重載 > 運算符,傳入greater<Type>()進行降序排列。這種方法只能針對一個維度排序,不靈活
  • 普通函數(shù):寫普通函數(shù)cmp,傳入cmp按照指定規(guī)則排列。這種方法可以對多個維度排序,更靈活
  • 仿函數(shù):寫仿函數(shù)cmp,傳入cmp<Type>()按照指定規(guī)則排列。這種方法可以對多個維度排序,更靈活

2. 自定義排序規(guī)則

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 普通函數(shù)

#include <bits/stdc++.h>
using namespace std;

struct Person {
	int id;
	int age;
	Person(int id,int age):id(id),age(age){}
};

//普通函數(shù)
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);//傳入函數(shù)指針cmp
	for (int i = 0; i < 4; i++) {
		cout << ps[i].id << " " << ps[i].age << endl;
	}
}

2.3 仿函數(shù)

#include <bits/stdc++.h>
using namespace std;

struct Person {
	int id;
	int age;
	Person(int id, int age) :id(id), age(age) {}
};

//仿函數(shù)
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()); //傳入函數(shù)指針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

欄目分類
最近更新