0

我有以下程序以小时:分钟:秒的形式比较时间。

class time
{
public:

    string Hours;
    string Minutes;
    string Seconds;
};

bool CompareTimes(time A, time B)
{
    if (A.Hours < B.Hours)
    {
        return true;
    }

    if (A.Minutes < B.Minutes)
    {
        return true;
    }

    if (A.Seconds < B.Seconds)
    {
        return true;
    }

    return false;
}

而在主要...

sort(TimeArray, TimeArray + NumberOfTimes, CompareTimes);

但是,这似乎无法正确排序。另一方面,如果我将 CompareTimes 方法更改为以下内容:

bool CompareTimes(time A, time B)
    {
        if (A.Hours > B.Hours)
        {
            return false;
        }

        if (A.Minutes > B.Minutes)
        {
            return false;
        }

        if (A.Seconds > B.Seconds)
        {
            return false;
        }

        return true;
    }

然后一切正常。我认为如果第二个输入大于第一个输入,排序函数需要返回 true。为什么它在第一种情况下不起作用,但在第二种情况下起作用?

4

2 回答 2

2
if (A.Hours < B.Hours)
{
        return true;
}

After that, you have two options: the hours are equal, or A.hours>B.hours. If they are equal, then it makes sense to compare the minutes. If A has more hours, then it makes no sense to compare the minutes. Your second condition should be:

if (A.Hours == B.Hours && A.Minutes < B.Minutes)

Similarly, your third condition should be:

if (A.Hours == B.Hours && A.Minutes == B.Minute && A.Seconds < B.Seconds)

The last return should remain the same. Also, be aware that storing these as strings will cause them to be ordered alphabetically. (or in order of their ASCII code).

于 2013-09-26T02:23:21.197 回答
0

I think to return true, you need to check all three conditions in one shot.

return (A.Hours*60*60 +A.Minutes*60+A.Seconds > B.Hours*60*60 + B.Minutes*60 + B.Seconds);

Just wrote the sample as below.

#include<iostream>
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
using namespace std;
class time_
{
public:
    string Hours;
    string Minutes;
    string Seconds;
    time_(int h,int m,int s){ 
        char buf[6]={0,};
        memset(buf,0,sizeof(buf));sprintf(buf,"%d",h);Hours+=buf;
        memset(buf,0,sizeof(buf));sprintf(buf,"%d",m);Minutes+=buf;
        memset(buf,0,sizeof(buf));sprintf(buf,"%d",s);Seconds+=buf;
    }   
};

bool CompareTimes(time_ A, time_ B){ 
    return (\
        ((atoi(A.Hours.c_str())*60*60)+(atoi(A.Minutes.c_str())*60)+atoi(A.Seconds.c_str())) > \
        ((atoi(B.Hours.c_str())*60*60)+(atoi(B.Minutes.c_str())*60)+atoi(B.Seconds.c_str())));
}
int main(){
    time_ A(10,10,10);
    time_ B(10,10,11);
    std::cout<<(CompareTimes( A, B)?"greater":"smaller")<<endl;
    time_ A1(10,11,10);
    time_ B1(10,10,10);
    std::cout<<(CompareTimes( A1, B1)?"greater":"smaller")<<endl;
}
于 2013-09-26T02:20:33.210 回答