我想对元素的索引进行排序而不是对切片进行排序。因为[]string{"dog","cat","apple","bat"}我想得到[]int{2,3,1,0}
package main
import (
"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]
}
守着一只汪
相关分类