繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM