sort sort

The default sort function is to sort in ascending order
sort(a,a+n);

The two parameters are the first and last addresses of the array to be sorted.

 

Sort in STL defaults to ascending lexicographical order. If we want to change the sorting order, we can use the third parameter of sort:

 

If you want a数组the elements to be arranged from large to small (or according to a certain rule), we can sortpass in a third parameter - "sort method"

sort(a, a + 5, greater<int>());

Among them, greaterit means "bigger", which means that the element type in the array to be sorted is , and the entire line of code means <int>to sort an array whose element type is integer from large to small.int

 

At this point the procedure is:

#include <iostream>
#include <algorithm>
using namespace std;
int main() 
{
    int a[] = { 3, 4, 5, 2, 1 };
    sort(a, a + 5, greater<int>());
    return 0;
}

 

 


Usage of Sorting in Structures

When using sort, we extend the structure:

struct constructor

struct Student{
    string name;
    int score;
    Student(){}
    Student(string n, int s):name(n), score(s){}
};

In addition to that, we can sort the struct:

There are two goals we want to achieve:

1. Sort in ascending lexicographical order based on student names

2. According to the grades of the students, if the grades of the first subject are the same, the grades of the second subject will be considered, and so on.

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

struct Student {
    string name;
    int score[4];
};

bool cmp_name(Student x,Student y){
	return x.name < y.name;
}

bool cmp_score(Student x, Student y){
    if(x.score[0] != y.score[0]){
        return x.score[0] > y.score[0];
    }
    if(x.score[1] != y.score[1]){
        return x.score[1] > y.score[1];
    }
    if(x.score[2] != y.score[2]){
        return x.score[2] > y.score[2];
    }
    return x.score[3] > y.score[3];
}

int main() {
    Student stu[3];
    for (int i = 0; i < 3; i++) {
        cin >> stu[i].name;
        for (int j = 0; j < 4; j++) {
            cin >> stu[i].score[j];
        }
    }
    sort(stu, stu + 3, cmp_name);
    for (int i = 0; i < 3; i++) {
        cout << stu[i].name << ":";
        for (int j = 0; j < 4; j++) {
            cout << stu[i].score[j] << " ";
        }
        cout<<endl;
    }
    sort(stu, stu + 3, cmp_score);
    for (int i = 0; i < 3; i++) {
        cout << stu[i].name << ":";
        for (int j = 0; j < 4; j++) {
            cout << stu[i].score[j] << " ";
        }
        cout<<endl;
    }
    
    return 0;
}

 

 

There is one thing to pay attention to - that is, you cannot use typedef to declare an array of structs at the same time

as follows:

 

typedef struct Student{
	string name;
	int a, b, c, d;
}stu[50];

This will report an error [Error] expected primary-expression before '[' token

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326282106&siteId=291194637