How to sort an array of dates in ascending order with C++

1 Answer

0 votes
#include <bits/stdc++.h> 

struct Date { 
    int day, month, year; 
}; 

bool compare(const Date &d1, const Date &d2) { 
    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; 

    return false; 
} 

int main() 
{ 
    Date arr[] = {{13,  2, 2007}, 
                  {19,  4, 2011},                   
                  {18,  4, 2011}, 
                  {1, 3, 1966}, 
                  {17,  5, 2019}, 
                  {17, 12, 1980}, 
                  {21,  6, 2017}, 
                  {17,  5, 2020}}; 
    int size = sizeof(arr)/sizeof(arr[0]); 
  
    std::sort(arr, arr + size, compare); 

    for (int i = 0; i < size; i++) { 
        std::cout << arr[i].day << "/" << arr[i].month << "/" << arr[i].year << "\n"; 
    } 
} 


/*
run:

1/3/1966
17/12/1980
13/2/2007
18/4/2011
19/4/2011
21/6/2017
17/5/2019
17/5/2020

*/

 



answered May 17, 2020 by avibootz

Related questions

2 answers 233 views
1 answer 135 views
1 answer 101 views
1 answer 159 views
1 answer 124 views
1 answer 119 views
1 answer 87 views
...