Go / Golang 对指向结构的指针切片进行排序

如何对指向结构的指针切片进行排序。我正在尝试根据开始时间对切片进行排序。


/**

 * 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

    

}


慕容森
浏览 107回答 2
2回答

芜湖不芜

发送一片,而不是一片片,你可以很好地排序:/*** Definition for an Interval.*/&nbsp;type Interval struct {&nbsp; &nbsp; &nbsp;Start int&nbsp; &nbsp; &nbsp;End&nbsp; &nbsp;int&nbsp;}func employeeFreeTime(schedule []*Interval) []*Interval {&nbsp; &nbsp; fmt.Println("Schedule initial #", schedule)&nbsp; &nbsp; sort.Slice(schedule, func(i,j int) bool{&nbsp; &nbsp; &nbsp; &nbsp; return schedule[i].Start < schedule[j].Start&nbsp; &nbsp; })&nbsp; &nbsp; fmt.Println(schedule)&nbsp; &nbsp; return nil}func main() {&nbsp; &nbsp; intervals :=&nbsp; []*Interval {&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Start: 10,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; End:&nbsp; &nbsp;100,&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Start: 5,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; End:&nbsp; &nbsp;100,&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; }&nbsp; &nbsp; employeeFreeTime(intervals)}

动漫人物

如果您想对Interval切片切片中的所有 s 进行排序。func employeeFreeTime(schedule [][]*Interval) []*Interval {&nbsp; &nbsp; var tempSlice []*Interval&nbsp; &nbsp; for _, slice := range schedule {&nbsp; &nbsp; &nbsp; &nbsp; tempSlice = append(tempSlice, slice...)&nbsp; &nbsp; }&nbsp; &nbsp; sort.Slice(tempSlice, func(i, j int) bool {&nbsp; &nbsp; &nbsp; &nbsp; return tempSlice[i].Start < tempSlice[j].Start&nbsp; &nbsp; })&nbsp; &nbsp; return tempSlice}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go