Sort an Array of dates in ascending order using Custom Comparator | C ++ implementation to sort the array of dates in the form of " DD - MM - YYYY " using custom comparator ; Comparator to sort the array of dates ; Condition to check the year ; Condition to check the month ; Condition to check the day ; Function that prints the dates in ascensding order ; Sort the dates using library sort function with custom Comparator ; Loop to print the dates ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int myCompare ( string date1 , string date2 ) { string day1 = date1 . substr ( 0 , 2 ) ; string month1 = date1 . substr ( 3 , 2 ) ; string year1 = date1 . substr ( 6 , 4 ) ; string day2 = date2 . substr ( 0 , 2 ) ; string month2 = date2 . substr ( 3 , 2 ) ; string year2 = date2 . substr ( 6 , 4 ) ; if ( year1 < year2 ) return 1 ; if ( year1 > year2 ) return 0 ; if ( month1 < month2 ) return 1 ; if ( month1 > month2 ) return 0 ; if ( day1 < day2 ) return 1 ; if ( day1 > day2 ) return 0 ; } void printDatesAscending ( vector < string > arr ) { sort ( arr . begin ( ) , arr . end ( ) , myCompare ) ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) cout << arr [ i ] << " STRNEWLINE " ; } int main ( ) { vector < string > arr ; arr . push_back ( "25-08-1996" ) ; arr . push_back ( "03-08-1970" ) ; arr . push_back ( "09-04-1994" ) ; arr . push_back ( "29-08-1996" ) ; arr . push_back ( "14-02-1972" ) ; printDatesAscending ( arr ) ; return 0 ; }