douren2831 2018-02-21 16:11
浏览 92
已采纳

如何在Go中嵌入和覆盖结构

I am constructing the min/max heaps of ints to satisfy the interface from container/heap.

The min heap works well such as

type MinHeapInt []int

func (h MinHeapInt) Len() int {
    return len(h)
}

func (h MinHeapInt) Less(i, j int) bool {
    return h[i] < h[j]
}

func (h MinHeapInt) Swap(i, j int) {
    h[i], h[j] = h[j], h[i]
}

func (h *MinHeapInt) Peek() interface{} {
    return (*h)[0]
}

func (h *MinHeapInt) Push(x interface{}) {
    *h = append(*h, x.(int))
}

func (h *MinHeapInt) Pop() interface{} {
    length := len(*h)
    res := (*h)[length - 1]
    *h = (*h)[0 : length - 1]
    return res
}

Now I am trying to develop the max heap by only overriding the Less method.

The first solution does not work since it cannot find the array

type MaxHeapInt struct {
    MinHeapInt
}

func (h MaxHeapInt) Less(i, j int) bool {
    return h[i] > h[j]
}

The second solution only keeps the Less method.

type MaxHeapInt MinHeapInt

func (h MaxHeapInt) Less(i, j int) bool {
    return h[i] > h[j]
}

Wonder if there is anyway to get around. Thanks!

  • 写回答

1条回答 默认 最新

  • douqin231881 2018-02-21 16:14
    关注

    Your first solution is trying to index the MaxHeapInt struct, not the MinHeapInt slice.

    type MaxHeapInt struct {
        MinHeapInt
    }
    
    func (h MaxHeapInt) Less(i, j int) bool {
        return h.MinHeapInt[i] > h.MinHeapInt[j]
    }
    

    If you want them to be initialized the same, then create a partial heap implementation, and wrap in the desired struct (similar to the wrapper example in the sort package).

    type Max struct{ IntHeap }
    
    func (h Max) Less(i, j int) bool {
        return h.IntHeap[i] > h.IntHeap[j]
    }
    
    type Min struct{ IntHeap }
    
    func (h Min) Less(i, j int) bool {
        return h.IntHeap[i] < h.IntHeap[j]
    }
    
    type IntHeap []int
    
    func (h IntHeap) Len() int { return len(h) }
    
    func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
    
    func (h *IntHeap) Peek() interface{} { return (*h)[0] }
    
    func (h *IntHeap) Push(x interface{}) {
        *h = append(*h, x.(int))
    }
    
    func (h *IntHeap) Pop() interface{} {
        length := len(*h)
        res := (*h)[length-1]
        *h = (*h)[0 : length-1]
        return res
    }
    
    // Now these can be initialized like
    //     Min{IntHeap{1, 2, 3}}
    //     Max{IntHeap{1, 2, 3}}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题