[英]Go / Golang Sort the slice of pointers to a struct
如何對指向結構的指針切片進行排序。 我正在嘗試根據開始時間對切片進行排序。
/**
* Definition for an Interval.
* type Interval struct {
* Start int
* End int
* }
*/
func employeeFreeTime(schedule [][]*Interval) []*Interval {
fmt.Println("Schedule initial #", schedule)
sort.Slice(schedule, func(i,j int) bool{
return schedule[i].Start < schedule[j].Start
})
fmt.Println(schedule)
return nil
}
發送一個切片,而不是一片切片,你可以很好地排序:
/**
* Definition for an Interval.
*/
type Interval struct {
Start int
End int
}
func employeeFreeTime(schedule []*Interval) []*Interval {
fmt.Println("Schedule initial #", schedule)
sort.Slice(schedule, func(i,j int) bool{
return schedule[i].Start < schedule[j].Start
})
fmt.Println(schedule)
return nil
}
func main() {
intervals := []*Interval {
{
Start: 10,
End: 100,
},
{
Start: 5,
End: 100,
},
}
employeeFreeTime(intervals)
}
如果您想對切片中的所有Interval
進行排序。
func employeeFreeTime(schedule [][]*Interval) []*Interval {
var tempSlice []*Interval
for _, slice := range schedule {
tempSlice = append(tempSlice, slice...)
}
sort.Slice(tempSlice, func(i, j int) bool {
return tempSlice[i].Start < tempSlice[j].Start
})
return tempSlice
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.