我如何对某物(如何比较两个切片)进行分类

发布于 2025-02-05 20:53:39 字数 652 浏览 1 评论 0原文

可以比较两个字符串:

package main

func main() {
    println("ab" > "ba")
    println("ab" < "ba")
}
false
true

Program exited.

https://go.dev/play/play/pplay/p/svklf6r84sc

如何在两个切片上执行类似的操作?例如[] int {1,2}&gt; [] int {2,1}

我需要将其排序一片ints。因此,我需要实现sort.interface

type Interface interface {
    Len() int
    Less(i, j int) bool
    Swap(i, j int)
}

如果此实现是通用的,那就更好了。

In Go is possible to compare two strings:

package main

func main() {
    println("ab" > "ba")
    println("ab" < "ba")
}
false
true

Program exited.

https://go.dev/play/p/svkLf6R84SC

How do I perform a similar operation on two slices? e.g. []int{1,2} > []int{2,1}.

I need this to sort a slice of slices of ints. So I need an implementation of sort.Interface.

type Interface interface {
    Len() int
    Less(i, j int) bool
    Swap(i, j int)
}

It would be better if this implementation is generic.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

み青杉依旧 2025-02-12 20:53:39

编写比较器和sort.slices的功能较小的功能是在标准库中执行此操作的最有效方法。
稍微逐步踩到该(直到标准库中的仿制用法最终确定),在GO 1.18中,我们可以使用golang.org/x/exp/constraints and code> golang.org/x/ EXP/SLICES jackages通常要排序有序值的切片: https:// go。 dev/play/p/p/ma0ly6povfr

func SortSlices[T constraints.Ordered](s [][]T) {
    sort.Slice(s, func(i, j int) bool {
        return slices.Compare(s[i], s[j]) < 0
    })
}

关于 slices .compare

比较比较S1和S2的元素。依次比较元素,从索引0开始,直到一个元素不等于另一个元素。比较第一个非匹配元素的结果被返回。如果两个切片都相等,直到其中一个切片结束,则将较短的切片视为小于较长的切片。如果S1 == S2,-1如果S1&lt; S2,+1如果S1&GT; S2。涉及浮点NAN的比较被忽略。

Writing a comparator and a less function for sort.Slices would be the most effective way to do this within the standard library.
Stepping outside of that slightly (until generics usage within the standard library is finalized), in Go 1.18 we can use the golang.org/x/exp/constraints and golang.org/x/exp/slices packages to generically sort a slice of slices of ordered values: https://go.dev/play/p/MA0lY6POVFR

func SortSlices[T constraints.Ordered](s [][]T) {
    sort.Slice(s, func(i, j int) bool {
        return slices.Compare(s[i], s[j]) < 0
    })
}

Documentation about slices.Compare:

Compare compares the elements of s1 and s2. The elements are compared sequentially, starting at index 0, until one element is not equal to the other. The result of comparing the first non-matching elements is returned. If both slices are equal until one of them ends, the shorter slice is considered less than the longer one. The result is 0 if s1 == s2, -1 if s1 < s2, and +1 if s1 > s2. Comparisons involving floating point NaNs are ignored.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文