I have been trying to figure this out for the past few hours so it's about time i search for help.
I was to use the Time class library and sort an array of time objects using the qsort function. I beleive my compare function is the problem and have tried different variations but still can't seem to grasp it.
Code:
#include <iostream>
#include "ccc_time.h"
using namespace std;
int tCompare(const void* , const void*) ;
void main()
{
Time* times[7] = {new Time(10, 13, 55), new Time(15, 13, 59), new Time(18, 7, 20), new Time(16, 10, 39),
new Time(9, 13, 45), new Time (16, 15, 24), new Time(17, 5, 8)};
cout << "unsorted times: " << endl;
for (int i =0; i < 7; i++)
cout<< times[i]->get_hours() << ":" << times[i]->get_minutes() << ":" << times[i]->get_seconds() << endl;
/* can't get to sort, beleive its something wrong with my compare function */
qsort(times, 7, sizeof(Time), tCompare);
cout << endl;
cout << "sorted times: " << endl;
for (int i =0; i < 7; i++)
cout<< times[i]->get_hours() << ":" << times[i]->get_minutes() << ":" << times[i]->get_seconds() << endl;
system ("pause");
}
int tCompare(const void* ptr1, const void* ptr2)
{
Time time1, time2;
time1 = *(Time *)ptr1;
time2 = *(Time *)ptr2;
/* can't get to sort, beleive its something wrong with my compare function,
this is not frist variation iv'e tried of the compare*/
if(time2.get_hours() - time1.get_hours() > 0)
return -1;
else if (time2.get_hours() - time1.get_hours() == 0 && time2.get_minutes() - time1.get_minutes() > 0)
return -1;
else if (time2.get_hours() - time1.get_hours() == 0 && time2.get_minutes() - time1.get_minutes() == 0
&& time2.get_seconds() - time1.get_seconds() > 0)
return -1;
else if (time2.get_hours() - time1.get_hours() == 0 && time2.get_minutes() - time1.get_minutes() == 0
&& time2.get_seconds() - time1.get_seconds() == 0)
return 0;
else
return 1;
}