如何在 C/C++ 中對日期陣列進行排序?
假設我們有一個日期陣列。此處我們將瞭解如何使用 C 或 C++ 程式碼對其進行排序。這些日期儲存在一個類中(C 中也可以使用結構)。我們將使用 C++ STL 的排序函式。為了比較日期,我們必須編寫要在排序函式中使用的自定義比較函式。讓我們看一看示例以便更好地理解。
示例
#include<iostream>
#include<iostream>
#include<algorithm>
using namespace std;
class Date {
public:
int d, m, y;
};
bool compare(const Date &date1, const Date &date2){
if (date1.y < date2.y)
return true;
if (date1.y == date2.y && date1.m < date2.m)
return true;
if (date1.y == date2.y && date1.m == date2.m && date1.d < date2.d)
return true;
return false;
}
void sortDateArray(Date arr[], int n) {
sort(arr, arr+n, compare);
}
int main() {
Date arr[] = {{20, 1, 2017},
{25, 3, 2010},
{ 3, 12, 1956},
{18, 10, 1982},
{19, 4, 2011},
{ 9, 7, 2013}};
int n = sizeof(arr)/sizeof(arr[0]);
sortDateArray(arr, n);
cout << "Sorted dates are" << endl;
for (int i=0; i<n; i++) {
cout << arr[i].d << " " << arr[i].m << " " << arr[i].y << endl;
}
}輸出
Sorted dates are 3 12 1956 18 10 1982 25 3 2010 19 4 2011 9 7 2013 20 1 2017
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP