duandao2306 2016-11-10 20:02
浏览 44
已采纳

空堆上的容器/堆Pop()

I have used the container/heap package to implement a priority queue. One thing bothers me though. What should the behaviour of the interface.Pop() method be if the heap is empty? I don't see anything mentioned in the documentation and the source code doesn't seem to be expecting this situation:

// Pop removes the minimum element (according to Less) from the heap
// and returns it. The complexity is O(log(n)) where n = h.Len().
// It is equivalent to Remove(h, 0).
//
func Pop(h Interface) interface{} {
        n := h.Len() - 1
        h.Swap(0, n)
        down(h, 0, n)
        return h.Pop()
}

Clearly, if h.Len() is 0 this is not going to work well. Is this simply meant to panic or is the user expected to always check whether there are any items left?

  • 写回答

1条回答 默认 最新

  • douyanjing8287 2016-11-11 00:25
    关注

    The natural behaviour is to panic. This is what the IntHeap example does.

    As pointed out in the comments, control will not reach h.Pop() if h.Swap() panics. However, h.Pop() can still be called on an empty heap if heap.Remove() is given -1 as the index:

    // Remove removes the element at index i from the heap.
    // The complexity is O(log(n)) where n = h.Len().
    //
    func Remove(h Interface, i int) interface{} {
        n := h.Len() - 1
        if n != i {
            h.Swap(i, n)
            down(h, i, n)
            up(h, i)
        }
        return h.Pop()
    }
    

    If h.Swap() panics on negative indices, h.Pop() should also panic for consistency.

    Having h.Swap() silently ignore negative indices and h.Pop() return a default value like nil is consistent, but other programmers would find that surprising so I don't recommend it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题