使用C++里自带的sort函数排序

sort函数是C++中自带的排序函数,包含在头文件 #include<algorithm> 的C++标准库中。

用sort函数排序比冒泡之类的算法效率要高

功能:对给定区间的所有元素进行排序,默认为升序,也可进行降序

   可以直接对数组进行排序

SYNTAX:

     sort(start, end, cmp);

start为数组的起始地址

end为数组结束地址的下一位

cmp为排序方式,可不填,默认升序

例:对年月日时间进行排序

 1 #include<iostream>
 2 #include<algorithm>
 3 using namespace std;
 4 class Date
 5 {
 6     public:
 7     int year;
 8     int month;
 9     int day;
10     int hour;
11     int startminute;
12     int endminute;
13 };
14 
15 int main()
16 {
17     Date arry[100];
18     void display(Date arry[], int n);
19     int n;
20     int i;
21     cout << "Please input the number of the date" << endl;
22     cin >> n;
23     cout << "Please enter year,month,day,hour,startminute,endminute in order" << endl;
24     for (i = 0; i < n; i++)
25     {
26             cin >> arry[i].year
27                 >> arry[i].month
28                 >> arry[i].day
29                 >> arry[i].hour
30                 >> arry[i].startminute
31                 >> arry[i].endminute;
32     }
33     display(arry, n);
34     return 0;
35 }
36 void display(Date arry[], int n)
37 {
38     int compare(Date a, Date b);
39     int i;
40     sort(arry, arry + n, compare);
41     cout << "Here are all the sorted date:" << endl;
42     for (i = 0; i < n; i++)
43     {
44         cout << "start time(" << arry[i].year << "/" << arry[i].month << "/" << "/" << arry[i].day;
45         cout << " " << arry[i].hour << ":" << arry[i].startminute << ") - ";
46         cout << "end time(" << arry[i].year << "/" << arry[i].month << "/" << "/" << arry[i].day;
47         cout << " " << arry[i].hour << ":" << arry[i].endminute << ")" << endl;
48         cout << "------------------------------------------" << endl;
49 
50     }
51 }
52 
53 int compare(Date a, Date b)
54 {
55     if (a.year == b.year)
56     {
57         if (a.month == b.month)
58         {
59             if (a.day == b.day)
60             {
61                 if(a.hour == b.hour)
62                 {
63                     return a.startminute<b.startminute;
64                 }
65                 else
66                 {
67                     return a.hour < b.hour;
68                 }
69             }
70             else
71             {
72                 return a.day < b.day;
73             }
74 
75         }
76         else
77         {
78             return a.month < b.month;
79         }
80     }
81     else
82     {
83         return a.year < b.year;
84     }
85 }
ps: 新手初学C++
原文地址:https://www.cnblogs.com/Hfolsvh/p/12785368.html