我试图在Go中对一片整数进行反向排序.
example := []int{1,25,3,5,4}
sort.Ints(example) // this will give me a slice sorted from 1 to the highest number
Run Code Online (Sandbox Code Playgroud)
如何对其进行排序以使其从最高到最低?所以[25 5 4 3 1]
我试过这个
sort.Sort(sort.Reverse(sort.Ints(keys)))
Run Code Online (Sandbox Code Playgroud)
资料来源:http://golang.org/pkg/sort/#Reverse
但是,我收到以下错误
# command-line-arguments
./Roman_Numerals.go:31: sort.Ints(keys) used as value
Run Code Online (Sandbox Code Playgroud)
tux*_*21b 53
sort.Ints是一个方便的函数来排序几个int.通常,如果要对sort和sort进行排序,则需要实现sort.Interface接口.Reverse只返回重新定义Less方法的接口的不同实现.
幸运的是,sort包中包含一个名为IntSlice的预定义类型,它实现了sort.Interface:
keys := []int{3, 2, 8, 1}
sort.Sort(sort.Reverse(sort.IntSlice(keys)))
fmt.Println(keys)
Run Code Online (Sandbox Code Playgroud)
小智 7
您可以仅使用以下命令来完成此操作,而不是使用两个函数调用和强制转换sort.Slice:
package main
import (
"fmt"
"sort"
)
func main() {
example := []int{1,25,3,5,4}
sort.Slice(example, func(a, b int) bool {
return example[b] < example[a]
})
fmt.Println(example)
}
Run Code Online (Sandbox Code Playgroud)
https://golang.org/pkg/sort#Slice
package main
import (
"fmt"
"sort"
)
func main() {
example := []int{1, 25, 3, 5, 4}
sort.Sort(sort.Reverse(sort.IntSlice(example)))
fmt.Println(example)
}
Run Code Online (Sandbox Code Playgroud)
输出:
[25 5 4 3 1]
Run Code Online (Sandbox Code Playgroud)