在Go语言中对无符号整数进行排序。

huangapple go评论69阅读模式
英文:

Sorting unsigned ints in Go

问题

我想对一个[]uint切片进行排序。这样做有意义吗?有没有什么关于uint类型使它们无法排序的问题?我注意到sort包中有IntSliceFloat64Slice,但没有uint的相关类型。

如果uint类型是可排序的,那么我是否可以直接复制sort.IntSlice中用于Len()Less(i, j int)Swap(i, j int)的实现呢?

英文:

I want to sort a slice of []uint. Does this make sense? Is there something I'm missing about uints that make them unsortable? I notice that the sort package has an IntSlice and Float64Slice, but nothing for uint.

If uints are sortable, then can I just copy the same implementation for Len(), Less(i, j int) and Swap(i, j int) that they've used for the sort.IntSlice?

答案1

得分: 4

关于1.7版本,你可以对任何实现了sort.Interface接口的切片进行排序,可以使用你的[]uint切片的别名类型,并使用sort.Sort(Interface)函数。在Go 1.8中,你还可以使用sort.Slice函数。可以在这里查看示例。

英文:

As for 1.7, you can sort any slice that implements sort.Interface for an alias type of your []uint slice and using sort.Sort(Interface) . In Go 1.8, you will have the option to use sort.Slice. See the example here

huangapple
  • 本文由 发表于 2017年1月13日 06:22:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/41624074.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定