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 如何实验stm32主通道和互补通道独立输出
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题