我想對(duì)元素的索引進(jìn)行排序而不是對(duì)切片進(jìn)行排序。因?yàn)閇]string{"dog","cat","apple","bat"}我想得到[]int{2,3,1,0}package mainimport ( "fmt" "sort" "strings")func main() { arr := []string{"dog","cat","apple","bat"} n := len(arr) indices := make([]int, n) for i:=0;i<n;i++{ indices[i]=i } sort.Slice(indices, func(i,j int) bool {return strings.Compare(arr[i],arr[j])<0}) fmt.Println(arr, indices) // [dog cat apple bat] [2 1 0 3] sort.Slice(arr, func(i,j int) bool {return strings.Compare(arr[i],arr[j])<0}) fmt.Println(arr) //[apple bat cat dog] }
切片索引排序
繁華開(kāi)滿天機(jī)
2022-12-05 11:15:33