Reprinted: c ++ sort usage, reprinted sort usage
Template used by the sort function:
Sort is included in the header file algorithm.
Sort (start, end, sorting method)
1. When there is no sorting method, the sorting is arranged from small to large by default. For example:
#include<iostream>#include<algorithm>using namespace std;int main(){ int a[10]={9,6,3,8,5,2,7,4,1,0}; for(int i=0;i<10;i++) cout<<a[i]<<endl;sort(a,a+10); for(int i=0;i<10;i++) cout<<a[i]<<endl; return 0;}
Next we will introduce the sorting method, that is, the comparison function complare.
1 # include <iostream> 2 3 # include <algorithm> 4 5 using namespace std; 6 7 bool complare (int a, int B) 8 9 {10 11 return a> B; 12 13} 14 15 int main () 16 17 {18 19 int a [10] = {9, 6 }; 20 21 for (int I = 0; I <10; I ++) 22 23 cout <a [I] <endl; 24 25 sort (a, a + 10, complare); // you do not need to input parameters to the complare function here. // This is Rule 26 27 for (int I = 0; I <10; I ++) 28 29 cout <a [I] <endl; 30 31 return 0; 32 33}
Example 3:
Although the method in the first and second examples above achieves sorting from big to small and from big to small, it is still a little troublesome to do so, because you also need to write a function that tells the program what sort principle to execute, the powerful functions of the c ++ standard library can completely solve this problem.
The third parameter of the Sortt function can be used to tell the program the sorting principle you adopt.
Less <data type> () // sort data in ascending order
Greater <data type> () // sort data in ascending order
In combination with this example, you can complete any sort principle you want.
#include<iostream>#include<algorithm>using namespace std;int main(){ int a[10]={9,6,3,8,5,2,7,4,1,0}; for(int i=0;i<10;i++) cout<<a[i]<<endl;sort(a,a+10,less<int>()); for(int i=0;i<10;i++) cout<<a[i]<<endl; return 0;}
#include<iostream>#include<algorithm>using namespace std;int main(){ int a[10]={9,6,3,8,5,2,7,4,1,0}; for(int i=0;i<10;i++) cout<<a[i]<<endl; sort(a,a+10,greater<int>()); for(int i=0;i<10;i++) cout<<a[i]<<endl; return 0;}
Example 4: Use the sort function to sort the characters. The sorting method is similar. The following shows an example of the program.
#include<iostream>#include<algorithm>using namespace std;int main(){ char a[11]="asdfghjklk"; for(int i=0;i<10;i++) cout<<a[i]<<endl; sort(a,a+10,greater<char>()); for(int i=0;i<10;i++) cout<<a[i]<<endl; return 0;}