前言:
學算法的第一天你在學冒泡、桶排
在你還沒搞明白快排和歸并的時候
你已經學到了數據結構最后的堆排序和希爾排序
可以說排序是很多競賽生的噩夢……
于是它誕生了
1
2
3
4
5
6
7
8
|
void std::sort() Sort the elements of a sequence using a predicate for comparison. 參數: __first – An iterator. __last – Another iterator. __comp – A comparison functor. |
針對一個地址區間完成排序,算法每次自動選擇,以快排為主
C++需要頭文件#include <algorithm>
(當然萬能頭我也沒意見)
1、升序排序
最簡單的就是用它完成int類型升序排序
1
2
3
4
5
6
7
8
9
|
Copy Line-numbers language-cpp #include <iostream> #include <algorithm> using namespace std; int main() { int a[5] = {2, 1, 3, 5, 4}; sort(a, a + 5); for ( int i = 0; i < 5; i++) cout << a[i] << " " ; } |
輸出如下,很簡單
1 2 3 4 5
這里傳入給sort的參數 a
和 a + 5
都是地址,和大多數編程語言一樣,這里遵循左閉右開原則,即函數實際會讀取和操作的五個地址如下:
1
2
3
4
5
|
a + 0 a + 1 a + 2 a + 3 a + 4 |
2、降序排序
如果需要降序排序,程序如下
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#include <iostream> #include <algorithm> using namespace std; bool cmp( int x, int y){ return x > y; } int main() { int a[5] = {2, 1, 3, 5, 4}; sort(a, a + 5, cmp); for ( int i = 0; i < 5; i++) cout << a[i] << " " ; } |
輸出:
5 4 3 2 1
我們多寫了一個bool類型的cmp函數,并將其地址作為第3個參數傳給了sort
cmp可以替換其內置的函數來判斷究竟該讓哪些元素在前哪些元素在后
很多小伙伴可能有個疑惑:如何從實質上理解cmp函數,或者說我究竟該怎么記住cmp怎么寫呢?
我們來看這三個點:
- 毋庸置疑,cmp函數返回bool類型,表示當前排序是否正確(具體見3)
- cmp函數應接受兩個參數,類型與要排序的數組相同(可以是int、short和long long這些常見類型,當然也可以是結構體)
-
cmp返回值的實際意義是傳入a、b兩個參數,a在前b在后的排序是否是正確的,若是正確的返回1(true),否則返回0(false)
那么我們再看一個結構體的排序實例
3、結構體的排序實例
結構體的排序實例:輸入10個學生的名字和成績,按照成績從高到低排序后輸出
輸入數據:
1
2
3
4
5
6
7
8
9
10
|
Yixiangzhilv 90 Mydr 60 Xiaoming 10 Mr.Glass 60 GZN 80 Wangzi 85 Hyx 100 Wyx 99 Xth 0 Zz 75 |
程序實現如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
#include <algorithm> #include <iostream> using namespace std; struct node { string name; int score; }; bool cmp( struct node x, struct node y) { return x.score > y.score; } int main() { struct node a[10]; for ( int i = 0; i < 10; i++) cin >> a[i].name >> a[i].score; sort(a, a + 10, cmp); for ( int i = 0; i < 10; i++) cout << a[i].name << " " << a[i].score << endl; } |
(此處還有一個C++知識:如果已經定義結構體node,那么 struct node a[10]; 和 node a[10]; 都是合法的)
以上就是詳解C++ sort函數的cmp參數的詳細內容,更多關于C++ sort函數的cmp參數的資料請關注服務器之家其它相關文章,希望大家以后多多支持服務器之家
原文鏈接:https://www.cnblogs.com/yxzl/p/cpp-sort-cmp.html?utm_source=tuicool&utm_medium=referral