问题描述
如何在Perl中为Heap :: Simple接口定义辅助顺序?
How do I define a secondary ordering to the Heap::Simple interface in Perl?
推荐答案
文档指出构造函数采用代码引用来定义顺序,因此您可以指定任何喜欢的排序方法:
The documentation states that the constructor takes a code reference to definethe order, so you can specify any sort method you like:
my $heap = Heap::Simple->new(order => \&sort_method);
如果$ key1小于$ key2,则返回true,否则返回false 否则价值. $ code_reference应该暗示总订单关系,所以它 需要具有传递性.
This should return a true value if $key1 is smaller than $key2 and a false value otherwise. $code_reference should imply a total order relation, so it needs to be transitive.
通过二次排序",我假设您的意思是在以下情况下使用第二次比较第一个显示值相等.假设第一个比较是通过"method1"方法找到的值,第二个比较是"method2"中的值.因此,如果方法1的值不同,则返回结果,否则退回到method2:
By "secondary ordering" I assume you mean that a second comparison is used ifthe first one shows the values to be equal. Let's say the first comparison isof values found via the "method1" method, and the second comparison is ofvalues from "method2". So, if by method1 the values are different, returnthat result, and otherwise fall back to method2:
sub sort_method
{
my ($val1, $val2) = @_;
my $result = ($val1->method1 <=> $val2->method1)
||
($val1->method2 <=> $val2->method2);
return 1 if $result == -1;
}
如果method1和method2返回字符串而不是数字值,则只需使用cmp
运算符而不是<=>
.您可以使用任何喜欢的东西,只要当操作员返回正确的值时.大多数排序功能,例如使用值-1、0和1来指示value1是否小于,等于或大于value2,但此模块喜欢1表示val1< val2,所以之后收集-1、0、1结果,如果结果为-1,则返回1(其中value1小于value2).
If method1 and method2 return strings instead of numeric values, simply usethe cmp
operator instead of <=>
. You can use anything you like, as longas the operator returns the right values. Most sort functions like using thevalues -1, 0 and 1 to indicate whether value1 is less than, equal to, orgreater than value2, but this module likes 1 to mean val1 < val2, so aftergathering the -1, 0, 1 result, one then returns 1 if the result is -1 (wherevalue1 is less than value2).
这篇关于堆中的二级订单::简单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!