📌  相关文章
📜  如何在C / C++中对日期数组进行排序?

📅  最后修改于: 2021-05-25 20:20:14             🧑  作者: Mango

给定日期数组,如何对它们进行排序。

例子:

Input:
       Date arr[] = {{20,  1, 2014},
                    {25,  3, 2010},
                    { 3, 12, 1676},
                    {18, 11, 1982},
                    {19,  4, 2015},
                    { 9,  7, 2015}}

Output:
      Date arr[] = {{ 3, 12, 1676},
                    {18, 11, 1982},
                    {25,  3, 2010},
                    {20,  1, 2014},
                    {19,  4, 2015},
                    { 9,  7, 2015}}

我们强烈建议您最小化浏览器,然后先尝试一下
我们的想法是使用内置函数来排序函数在C++中。我们可以编写自己的比较函数,该函数首先比较年份,然后比较几个月,然后比较几天。

下面是一个完整的C++程序。

// C++ program to sort an array of dates
#include
using namespace std;
  
// Structure for date
struct Date
{
    int day, month, year;
};
  
// This is the compare function used by the in-built sort
// function to sort the array of dates.
// It takes two Dates as parameters (const is
// given to tell the compiler that the value won't be
// changed during the compare - this is for optimization..)
  
// Returns true if dates have to be swapped and returns
// false if not. Since we want ascending order, we return
// true if the first Date is less than the second date
bool compare(const Date &d1, const Date &d2)
{
    // All cases when true should be returned
    if (d1.year < d2.year)
        return true;
    if (d1.year == d2.year && d1.month < d2.month)
        return true;
    if (d1.year == d2.year && d1.month == d2.month &&
                              d1.day < d2.day)
        return true;
  
    // If none of the above cases satisfy, return false
    return false;
}
  
// Function to sort array arr[0..n-1] of dates
void sortDates(Date arr[], int n)
{
    // Calling in-built sort function.
    // First parameter array beginning,
    // Second parameter - array ending,
    // Third is the custom compare function
    sort(arr, arr+n, compare);
}
  
// Driver Program
int main()
{
    Date arr[] = {{20,  1, 2014},
                  {25,  3, 2010},
                  { 3, 12, 1676},
                  {18, 11, 1982},
                  {19,  4, 2015},
                  { 9,  7, 2015}};
    int n = sizeof(arr)/sizeof(arr[0]);
  
    sortDates(arr, n);
  
    cout << "Sorted dates are\n";
    for (int i=0; i

输出:

Sorted dates are
3 12 1676
18 11 1982
25 3 2010
20 1 2014
19 4 2015
9 7 2015

同样在C语言中,我们可以使用qsort()函数。

相关问题:
如何有效地对20年代的大列表日期进行排序

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”