Im creating a program for a race. The Race class has a vector of results and each element of that vector is a pointer to a result. The Result class has a Time and a pointer to a Participant. So in each race there are various results and it is a result for each participant.
The Time is a class that has hours, minutes and seconds.
How can I sort the vector of results from the result of the participant with the fastest time to the result of the participant with the slowest time?
My code is like this:
If you want to pass a pointer by reference (although you don't need to here) you've got the syntax wrong:
bool isFaster(Result*& a, Result*& b)
But, as I said, that isn't necessary. Nor is it necessary for your comparison function to be a member of Result. Your comparison is a typical less-than comparison so the name should reflect that, isFastest does not.
After numerous changes to make your code const correct, the function might look like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
bool isFaster(const Result* a, const Result* b)
{
const Time aTime = a->getTime();
const Time bTime = b->getTime();
if (aTime.getHours() < bTime.getHours())
returntrue;
if (aTime.getMinutes() < bTime.getMinutes())
returntrue;
return aTime.getSeconds() < bTime.getSeconds();
}
void Race::sortResults() {
sort(results.begin(), results.end(), isFaster);
}
The implementation would go in the cpp file. There isn't necessarily any reason to include a declaration/prototype in the .h file since it doesn't need to be visible to code using the class interface.
I think cire's isFaster() may not be quite right. For example, if aTime is 10:11:12 and bTime is 12:20:21, it will think that aTime < bTime. The right code is more like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
bool isFaster(const Result* a, const Result* b)
{
const Time aTime = a->getTime();
const Time bTime = b->getTime();
if (aTime.getHours() < bTime.getHours())
returntrue;
if (aTime.getHours() > bTime.getHours())
returnfalse;
// hours are equal.
if (aTime.getMinutes() < bTime.getMinutes())
returntrue;
if (aTime.getMinutes() > bTime.getMinutes())
returnfalse;
// Minutes are equal
return aTime.getSeconds() < bTime.getSeconds();
}
Thank you very much for your help.
I put the isFaster function in the .cpp file but I get two errors:
First in both this lines:
const Time aTime = a->getTime();
const Time bTime = b->getTime();
I get this error:
Multiple markers at this line
- Invalid arguments ' Candidates are: Time getTime() '
- passing 'const Result' as 'this' argument of 'Time Result::getTime()' discards qualifiers [- fpermissive]
Then in every line that has an if i get:
Multiple markers at this line
- Invalid arguments ' Candidates are: unsigned int getHoras() '
- Invalid arguments ' Candidates are: unsigned int getHoras() '
- passing 'const Tempo' as 'this' argument of 'unsigned int Tempo::getHoras()' discards
qualifiers [-fpermissive]