如何优化自定义日期结构的比较功能? [英] How can I optimize compare function for custom date structure?
问题描述
我想对 date
s的向量进行排序,并为此编写了compare函数:
I want to sort a vector of date
s and I wrote compare function for it:
#include <iostream>
struct date {
int day;
int month;
int year;
};
int compare_dates(date a, date b) {
if (a.year < b.year) {
return -1;
} else if (a.year == b.year) {
if (a.month < b.month) {
return -1;
} else if (a.month == b.month) {
if (a.day < b.day) {
return -1;
} else if (a.day > b.day) {
return 1;
}
} else {
return 1;
}
} else {
return 1;
}
return 0;
}
int main() {
date a = {};
date a.day = 19;
date a.month = 11;
date a.year = 2016;
date b = {};
date b.day = 20;
date b.month = 11;
date b.year = 2016;
compare_dates(a, b) // -1
compare_dates(b, a) // 1
compare_dates(b, b) // 0
return 0;
}
运行良好,但 compare_dates
函数看起来很糟糕。有什么想法可以改进吗?
It is working well, but compare_dates
function looks awful. Is there any idea how can I improve it?
推荐答案
我不是C ++专家,其他人则指出 std :: sort()
不需要三向比较,只需要<
。但是要按书面形式清理代码:
I'm not a C++ expert and the others are pointing out that std::sort()
doesn't require three-way comparison, only a <
. But to clean up your code as written:
您的 compare_dates()
始终对<$进行三向比较c $ c>> /< / == ,并希望返回值 + 1 / -1 / 0
。因此,声明一个三向 cmp()
帮助器函数,就像在Python中一样。现在您的代码简化为:
Your compare_dates()
keeps doing three-way comparisons for >/</==
, and wants a +1/-1/0
return value. So declare a three-way cmp()
helper function which does that, like we do in Python. Now your code reduces to:
int cmp(int x, int y) {
return (x>y) ? 1 : ((x<y) ? -1 : 0);
}
int compare_dates(date a, date b) {
if (cmp(a.year, b.year) != 0)
return cmp(a.year, b.year);
if (cmp(a.month, b.month) != 0)
return cmp(a.month, b.month);
return cmp(a.day, b.day);
}
订单比较结果为 ==。这样一来,您就可以避免所有其他的子句,花括号和缩进,这可以使您的缩进级别保持恒定,并且易于观察。它还指出了计算的对称性。
You only fall-through into doing the lower-order comparisons if the higher-order comparison gave '=='. So that allows you to avoid all the else-clauses, braces and indenting, which keeps your indent level constant and is easy on the eyes. It also calls out the symmetry of the computations.
这篇关于如何优化自定义日期结构的比较功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!