Sort by date

Hi all, I'm trying to sort by age a vector of birthday dates.
I'm using the functions in the <ctime> header to calculate the difference in seconds between two date but it doesn't work! If I try to print 2 different dates with asctime() or ctime() it either prints 2 time the same date or throws an exception! I post my code below:
p.s.: I'm using a wrapper class called Date.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <ctime>
#include <iostream>
#include <conio.h>
#include <vector>
#include <cstdlib>
#include <iterator>
#include <iomanip>
#include <algorithm>
using namespace std;

class Date
{
public:
	Date(int d, int m, int y) :day(d), month(m), year(y) { }
	int day; // 1 - 31
	int month; // 0 - 11
	int year;
};

ostream& operator<<(ostream& out, const Date& right)
{
	return out << setw(2) << setfill('0') << right.day << " " 
                   << setw(2) << setfill('0') << right.month << " " 
                   << right.year;
}

class ageCMP
{
public:
	bool operator()(const Date& left, const Date& right)
	{
		tm tml = { 0, 0, 0, left.day, left.month, left.year - 1900 };

		tm tmr = { 0, 0, 0, right.day, right.month, right.year - 1900 };
		time_t lt = mktime(&tml);
		time_t rt = mktime(&tmr);

		cout << left << endl;
		cout << right << endl;

		/* Error */
		cout << asctime(&tml) << endl;
		cout << asctime(&tmr) << endl;
		cout << ctime(&lt) << endl;
		cout << ctime(&rt) << endl;

		cout << "Press a key..." << endl;
		_getch();
		return difftime(lt, rt) < 0;
	}
};

int main()
{
	srand(time(NULL));
	vector<Date> date;
	const int N = 30;
	for (int i = 0; i < 30; ++i)
	{
		date.push_back(Date(rand() % 31 + 1, 
                   rand() % 12, rand() % (2015 - 1900) + 1900));
	}
	sort(date.begin(), date.end(), ageCMP());

	copy(date.begin(), date.end(), ostream_iterator<Date>(cout, "\n"));
	cout << "Press a key...";
	_getch();
	return 0;
}
Well, I didn't try to debug your entire code. I do think there are errors in the ageCMP function.

As an alternative, for purposes of sorting you could do this:
1
2
3
4
5
6
bool Date::operator <(const Date & rhs) const
{
    unsigned long left  = year     * 10000 + month     * 100 + day;
    unsigned long right = rhs.year * 10000 + rhs.month * 100 + rhs.day;
    return left < right;
} 

after adding the < operator, sort like this:
 
    sort(date.begin(), date.end());


My suggestion simply constructs an 8-digit integer from the year, month, day values. If you tried to do complicated arithmetic with the date in that format, things would go horribly wrong, but for a simple less-than comparison it should be fine.

Topic archived. No new replies allowed.