[英]Go / Golang Sort the slice of pointers to a struct
How do I sort slice of pointer to a struct.如何对指向结构的指针切片进行排序。 I am trying to sort the slice based on the start time.我正在尝试根据开始时间对切片进行排序。
/**
* 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
}
Send in a slice, instead of a slice of slices and you can sort just fine:发送一个切片,而不是一片切片,你可以很好地排序:
/**
* 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)
}
In case you want to sort all the Interval
s among the slice of slice.如果您想对切片中的所有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.