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}}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计