2 Star 2 Fork 7

王布衣 / gox

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
slices_sort.go 1.00 KB
一键复制 编辑 原始数据 按行查看 历史
王布衣 提交于 2023-08-13 11:51 . 升级go版本到1.21.0
package api
import (
"reflect"
"slices"
"sort"
)
// SliceSort slice排序
func SliceSort[S ~[]E, E any](slice S, less func(a, b E) bool) {
sort.Slice(slice, func(i, j int) bool {
a := slice[i]
b := slice[j]
return less(a, b)
})
}
// SliceUnique sorts the slice pointed by the provided pointer given the provided
// less function and removes repeated elements.
// The function panics if the provided interface is not a pointer to a slice.
func v1SliceUnique[S ~[]E, E any](slicePtr *S, less func(i, j int) bool) {
v := reflect.ValueOf(slicePtr).Elem()
if v.Len() <= 1 {
return
}
sort.Slice(v.Interface(), less)
i := 0
for j := 1; j < v.Len(); j++ {
if !less(i, j) {
continue
}
i++
v.Index(i).Set(v.Index(j))
}
i++
v.SetLen(i)
}
func SliceUnique[S ~[]E, E any](slice S, compare func(a E, b E) int) S {
//v := reflect.ValueOf(&slice).Elem()
//slices.SortFunc()
slices.SortFunc(slice, compare)
s := slices.CompactFunc(slice, func(a E, b E) bool {
return compare(a, b) == 0
})
return s
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/quant1x/gox.git
git@gitee.com:quant1x/gox.git
quant1x
gox
gox
v1.21.2

搜索帮助