2013-09-26 69 views
0

我有以下程序以小时:分钟:秒的形式比较时间。在C++中用对象对函数进行排序?

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; 
    } 

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

+3

只需使用'std :: tie'并比较得到的元组。 – chris

+0

[运算符<和严格弱排序](http://stackoverflow.com/q/979759/1639256)或[如何将bool映射到具有std :: map的3d点结构?](http:/ /stackoverflow.com/q/6109445/1639256)(我更喜欢后者的接受答案) – Oktalist

回答

0

我认为要返回true,你需要在一次检查中检查所有三个条件。

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

只写了下面的示例。

#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; 
} 
2
if (A.Hours < B.Hours) 
{ 
     return true; 
} 

之后,你有两个选择:时间是相等的,或A.hours> B.hours。如果他们是平等的,那么比较分钟是有意义的。如果A有更多的时间,那么比较分钟就没有意义了。 你的第二个条件应该是:

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

同样,你的第三个条件应该是:

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

最后的回报应保持不变。 另外,请注意将它们存储为字符串将使它们按字母顺序排列。 (或按照他们的ASCII码顺序)。