c / c ++ in sort function usage

Reprinted from bloggers: Jiujiang Town in https://www.cnblogs.com/jjzzx/

Use the sort function of c ++ standard library

I) Sort function is included in c ++ standard library header files to #include <algorithm>, the sorting method calls the standard library may not have to know how its interior is achieved as long as the emergence of results we want to!

II) Sort function takes three parameters:

(1) The first is to sort the start address of the array.

(2) The second is the end of the address (the last one to sort of address)

(3) The third parameter is the sort of method, but also can be big to small from small to large, you can not write the third parameter, then the default is to sort in ascending order.

Sort function using templates:

Sort (start, end, sorted)

Here's the specific use sort () function in conjunction with an array of dozens of sorts make a note!

Example a: sort function has no third parameter, from small to large is achieved

Copy the code
 1 #include<iostream>
 2 
 3 #include<algorithm>
 4 using namespace std;
 5 int main()
 6 {
 7    int a[10]={9,6,3,8,5,2,7,4,1,0};
 8    for(int i=0;i<10;i++)
 9    cout<<a[i]<<endl;
10   sort(a,a+10);
11    for(int i=0;i<10;i++)
12    cout<<a[i]<<endl;
13    return 0;
14 }
Copy the code

 

Example Two

By the example above, would the question: To achieve descending sort swollen do?

 Which as previously mentioned the need to make a fuss in the function's third argument sort (), the program I want to tell descending order!

A comparison function need to add complare (), implementation of this function is such that

bool complare(int a,int b)
{
    return a>b;
}

 

 

  This is how to tell the program to achieve the sort of descending!

Copy the code
#Include. 1 <the iostream> 
 2 #include <algorithm> 
 . 3 the using namespace STD; 
 . 4 BOOL complare (A int, int B) 
 . 5 { 
 . 6 return A> B; 
 . 7} 
 . 8 int main () 
 . 9 { 
10 int A [10] {9,6,3,8,5,2,7,4,1,0} =; 
. 11 for (int I = 0; I <10; I ++) 
12 is COUT << A [I] << endl; 
13 is sort (a, a + 10, complare); // where there is no need to pass the function parameters complare, 
14 // this is the rule 
15 for (int I = 0; I <10; I ++) 
16 << COUT A [I] << endl; 
. 17 return 0; 
18 is}
Copy the code

 Assume that you define a structure node

Copy the code
1 struct node
2 {
3   int a;
4   int b;
5   double c;
6 }
Copy the code

The array has a node type of node arr [100], I would like to sort: a press value in ascending order, if the a values ​​are the same, then the value of b in descending order, if b is also the same Click c in descending order. I can write a comparison function:

The following is the code fragment:

Copy the code
1 bool cmp(node x,node y)
2 {
3    if(x.a!=y.a) return x.a<y.a;
4    if(x.b!=y.b) return x.b>y.b;
5    return x.c>y.c;
6 }
 
 
 
Copy the code

Guess you like

Origin www.cnblogs.com/epep/p/10959627.html