天天看點

實用sort函數

加粗樣式`

1、sort函數的基本使用。

// algorithm 譯:算法。
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	// 學會使用 sort排序函數
	// 1、将整數排序;
	int a[] = {3, 6, 1, 5, 2, 4};
	int n1 = 6;						// 将該數組中的前n項排序; 
	sort(a,a+n1); 					// sort(首元素位址(必填), 尾元素位址的下一個位址(必填), 比較函數(非必填)): 
	// 因為對其操作的是指針,是以我們不需要傳回值,直接列印出來。
	for (int i = 0; i < n1; i++) {
		cout << a[i] << " ";
	} 
	cout << endl;
	// ----------------》在預設前提下,該sort函數是按 遞增 排序得到。
	
	// 2、對double排序;
	double b[] = {6.6, -3, 2.6, 9.8}; 
	int n2 = 4;
	sort(b,b + n2);
	for (int i = 0; i < n2; i++) {
		cout << b[i] << " ";
	}
	cout << endl;
	
	// 3、對char型數組排序 (預設按字典順序) 
	char c[] = {'e','r','u','a'};
	int n3 = 4;
	sort(c,c + n3);
	for (int i = 0; i < n3; i++) {
		cout << c[i] << " ";
	} 
	
	
	// 未完待續... 
	
	
	return 0;
} 
           

2、使用sort函數進行一些簡單的排序。

#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
// 1、cmp函數; 
bool cmp1(int a, int b) {
	return a > b;
}
// 2、一般在我們實際做題當中大多會遇到一個結構體,比方說:總分相同的前提下,再按國文成績排序這樣的,cmp函數如下:

struct stu1{
	string name;
	int number;
	int score;
	int chine; 
};
bool cmp2(stu1 a, stu1 b)
{
	if (a.score != b.score)
		return a.score > b.score;
	else
		return a.chine > b.chine;	
}
// 3.用于我們實際生活中的成績排序; 
struct stu2{
	string name;
	string number;			// 建議這裡的學号設成字元串形式,因為這樣才更好比較兩個大于10位數的學号,因為int型最高是10位。 
	int score;
	int chine; 
	int rank;		// 新加的排名。 
}; 
bool cmp3(stu2 a, stu2 b) {
	if (a.score != b.score)
		return a.score > b.score;
	else
		return a.number.compare(b.number) < 0;	 
} 
int main() 
{
	// 上接1:但是我們如果是想得到從大到小的排序,就要用到 cmp函數,下面我們就來寫cmp函數。 
	int a[] = {3, 6, 9, 2}; 
	sort(a, a + 4, cmp1);
	for (int i = 0; i < 4; i++) {
		cout << a[i] << " "; 
	}
	cout << endl;
	// 輸出結果: 9 , 6, 3, 2; 
	
	// 2.上接上面結構體題;
	
	stu1 str[] = {{"wen",111,386,88},{"you",222,386,99},{"yang",333,459,99}}; 
	sort(str,str + 3,cmp2);
	for (int i = 0; i < 3; i++) {
	 	cout << str[i].name << " " <<  str[i].number << " " << str[i].score << " " << str[i].chine << endl;
	}
	cout << endl;
	
	// 3.一般我們用在學生成績的排序上時,會遇到如果兩個同學總分相同的前提下,會給兩個同學安排一養的名次。
	// 	 當然在此之後的同學 排名還是要靠後的,舉個例子:400,369,369,356;最後給出來的排名是400-1;369-2;369-2;356-4;
	//   然後我們可以把排名在定義結構體時就加上去。
	stu2 str2[] = {{"文","111",450, 109}, {"有","222",450,117}, {"梅","333",405,108}}; 
	sort(str2,str2 + 3, cmp3);
	str2[0].rank = 1;
	for (int i = 1; i < 3; i++) {
		if (str2[i].score == str2[i-1].score)
			str2[i].rank = str2[i-1].rank;
		else
			str2[i].rank = i + 1;				// 如果成績不相等的話就得名次就是i + 1;	
	}
	for (int i = 0; i < 3; i++) {
		cout << str2[i].name << " " <<  str2[i].number << " " << str2[i].score << " " << str2[i].chine << " " << str2[i].rank << endl;
	} 
	
	
	// 這兒還有一種排序方法,不用在定義結構體時加入排名,因為有些時候我們有排名可以輸出便可,如下:
	/*
	int r = 1;
	cout << r " ";
	for (int i = 0; i < n; i++) {
		if (str2[i].score != str2[i].score)
			r = i + 1;
		// else	r不變;
		cout << r << " "; 	
	}
	
		
	*/ 
	return 0;
}
           

謝謝觀看。

繼續閱讀