我有以下程序以小時:分鐘:秒的形式比較時間。在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。爲什麼它在第一種情況下不起作用,但在第二種情況下工作?
只需使用'std :: tie'並比較得到的元組。 – chris
[運算符<和嚴格弱排序](http://stackoverflow.com/q/979759/1639256)或[如何將bool映射到具有std :: map的3d點結構?](http:/ /stackoverflow.com/q/6109445/1639256)(我更喜歡後者的接受答案) – Oktalist