sort函數詳解

sort函數作爲算法庫內自帶的排序算法,極大地減少了程序猿在編寫排序所花的時間。要使用sort函數,只需引入頭文件#include<algorithm>

函數寫法爲 sort(begin,end)

例如:

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

int main()
{
	int a[10] = { 5, 51, 1, 3, 9, -1, 10, 9, 4, 0 };
	sort(a, a + 10);
	cout << "after sort: ";
	for (int i = 0; i < 10; i++){
		cout << a[i] << ' ';
	}
	return 0;
}

輸出結果爲:

默認排序爲升序排序,那麼又怎樣利用它進行降序排序呢?

1.爲了滿足不同情況排序的要求,sort函數在end後還可以加一個比較函數,即接受含三個參數的sort;

sort(begin,end,compare)

例如,爲滿足降序排序的需求

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

bool compare(int a, int b){
	return a > b;
}
int main()
{
	int a[10] = { 5, 51, 1, 3, 9, -1, 10, 9, 4, 0 };
	sort(a, a + 10,compare);
	cout << "after sort: ";
	for (int i = 0; i < 10; i++){
		cout << a[i] << ' ';
	}
	return 0;
}

輸出結果爲

2.對<進行運算符重載,因爲sort主要是通過<來排序,在對類的排序中較爲實用

3.利用functional標準庫

其實c++標準庫中已有現成可用的比較運算符,在頭文件中引用include進來即可。

#include<functional>

其中functional提供瞭如下的基於模板的比較函數對象。

1.equal_to<type>:等於;

2.not_equal_to<type>:不等於;

3.greater<type>:大於;

4.greater_equal<type>:大於等於;

5.less<type>:小於;

6.less_equal<type:小於等於。

例如:

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

int main()
{
	int a[10] = { 5, 51, 1, 3, 9, -1, 10, 9, 4, 0 };
	sort(a, a + 10,greater<int>());
	cout << "after sort: ";
	for (int i = 0; i < 10; i++){
		cout << a[i] << ' ';
	}
	return 0;
}

就完成了降序排序

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