堆中的二级订单::简单 [英] Secondary Order in Heap::Simple

查看:116
本文介绍了堆中的二级订单::简单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在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 define the order, so you can specify any sort method you like:

my $heap = Heap::Simple->new(order => \&sort_method);

每次需要比较两个键时,给定的代码引用将被调用为: $ less = $ code_reference->($ key1,$ key2);

Every time two keys need to be compared, the given code reference will be called like: $less = $code_reference->($key1, $key2);

如果$ 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 if the first one shows the values to be equal. Let's say the first comparison is of values found via the "method1" method, and the second comparison is of values from "method2". So, if by method1 the values are different, return that 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 use the cmp operator instead of <=>. You can use anything you like, as long as the operator returns the right values. Most sort functions like using the values -1, 0 and 1 to indicate whether value1 is less than, equal to, or greater than value2, but this module likes 1 to mean val1 < val2, so after gathering the -1, 0, 1 result, one then returns 1 if the result is -1 (where value1 is less than value2).

这篇关于堆中的二级订单::简单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆