duanmou9228 2018-01-18 23:05
浏览 32
已采纳

排序时忽略nil个元素

For sorting such struct I implemented three methods:

type Event struct {
    timeEnd interface{}
    size float64
}

func (s ByTime) Len() int {
    return len(s)
}
func (s ByTime) Swap(i, j int) {
    s[i], s[j] = s[j], s[i]
}

Sometimes not all Events.timeEnd are initialized and I want to put such Events into the back of slice and sorting them by size field.

func (s ByTime) Less(i, j int) bool {
    if s[i].timeEnd == nil || s[j].timeEnd == nil{
        return s[i].size < s[j].size
    }else {
        return s[i].timeEnd.(float64) < s[j].timeEnd.(float64)
    }
}

 a, b, c, d := Event{timeEnd:12.}, Event{timeEnd:nil, size:-10}, Event{timeEnd:56.}, Event{timeEnd:nil, size:2}
 queue := []*Event{}
 queue = append(queue, &a, &b, &c, &d) 

But as result I have:

[<nil> 12 56 <nil>] 

While expecting [12 56 <nil> <nil>] How to implement it correctly?

Here example in https://play.golang.org/p/FWU98npGtbU

  • 写回答

1条回答 默认 最新

  • doudi7570 2018-01-18 23:17
    关注

    In Less, you don't want to compare the sizes unless both timeEnds are nil and then you'd need to handle the "only one timeEnd is nil" cases separately. So you have four cases to consider not two:

    func (s ByTime) Less(i, j int) bool {
        if s[i].timeEnd == nil && s[j].timeEnd == nil{
            return s[i].size < s[j].size
        } else if s[i].timeEnd == nil {
            return false
        } else if s[j].timeEnd == nil {
            return true
        } else {
            return s[i].timeEnd.(float64) < s[j].timeEnd.(float64)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)