STL中sort總結

前言

平時寫算法題時經常會用的到sort排序,本文將會從sort原理,sort在結構體,vector,map中使用方法總結

sort原理

1.數據量大時採用QuickSort快排算法,分段歸併排序。

2.一旦分段後的數據量小於某個門檻(16),爲避免QuickSort快排的遞歸調用帶來過大的額外負荷,就改用Insertion Sort插入排序。

3.如果遞歸層次過深,還會改用HeapSort堆排序。

sort的倆種排序方式

1.從小到大(默認)
sort(nums.begin(), nums.end(),less());
2.從大到小
sort(nums.begin(), nums.end(),greater())

比較函數

針對不同的結構可以寫自己的比較函數,但是比較函數要注意傳的參數就是模板的類型,比如對vector排序就是傳int類型

sort對結構體排序

例如對node從大到小排序

#include <iostream>
#include <algorithm>
using namespace std;
struct node
{
	int a;
	int b;
};
int main()
{
	node nums[5];
	for (int i = 0; i < 5; ++i)
	{
		nums[i].a = i;
		nums[i].b = i;
	}
	sort(nums, nums + 5, [&](const node& a, const node& b) {return a.a > b.a; });
	for (int i = 0; i < 5; ++i)
	{
		cout << nums[i].a <<"  "<< nums[i].b << endl;
	}
	return 0;
}

在這裏插入圖片描述

sort對vector排序

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main()
{
	vector<int> nums = { 1,4,2,5,3,7 };
	sort(nums.begin(), nums.end(), [&](const int& a, const int& b) {return a < b; });
	for (int i : nums)
		cout << i<<endl;
	return 0;
}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章