首页 > 解决方案 > Julia SortedSet 中的自定义排序

问题描述

在 SortedSet 的 Julia 文档中,有一个对“排序对象”的引用,可以在构造函数中使用。我正在做一个项目,我需要在一组结构上实现自定义排序。我想为此使用仿函数,因为我需要额外的状态进行比较。这是我要解决的问题的简化版本。我有两个结构,点和边:

struct Point{T<:Real}
    x::T
    y::T
end
struct Edge{T<:Real}
    first::Point{T}
    second::Point{T}
end

我有一个名为“vantage”的,我想根据边缘与“vantage”的距离来排序。从概念上讲:

function edge_ordering(vantage::Point, e1::Edge, e2::Edge)
    d1 = distance(vantage, e1)
    d2 = distance(vantage, e2)
    return d1 < d2
end

“排序对象”是仿函数(或仿函数)吗?在 Julia 中是否有其他传统的排序方式?

标签: julia

解决方案


排序基于isless类型的方法。因此,例如,如果您有一个要在b字段中排序的类型。例如你可以做

struct Foo{T}
        a::T
        b::T
end

Base.:isless(x::T,y::T) where {T<:Foo} = isless(x.b,y.b)

s=[Foo(1,2),Foo(2,-1)]

res=SortedSet(s)
#SortedSet(Foo[Foo(2, -1), Foo(1, 2)],
#Base.Order.ForwardOrdering())

元组也是按顺序排序的,因此您也可以使用 sort(s,by=x->(x.b,x.a))排序依据b,然后a不必定义isless类型。


推荐阅读