【问题标题】:How do you use the heap package in Go?在 Go 中如何使用 heap 包?
【发布时间】:2022-02-02 11:43:20
【问题描述】:

我一直在尝试在 Go 中使用 Heap 包,但我不确定如何初始化它。

package main
import "container/heap"

type PriorityMessage struct {
    Priority int
    Message string
}

func priorityQueue() {
    //WOULD THIS not initialize the heap?
    h := heap.Init(h PriorityMessage)

}

我一直试图在网上找到其他人如何初始化他们的堆的示例,并且他们似乎每次都创建自己的 Go 堆包版本。从 heap 包调用 heap.Init(h Interface) 函数不起作用吗?

【问题讨论】:

  • 这就是我所困惑的,就像在这个例子中他们如何创建 push、pop、len .etc 函数一样,每次你想使用堆时,你必须将这些函数编写为好吧,或者你可以从堆包中调用它吗?
  • 参见Interface 文档。该应用程序提供了用于访问底层数据的简单操作。 heap 包使用这些操作来实现堆语义。
  • @paartrk 是的,当然。
  • 您可以在这篇文章中看到container/heap 包的用法以及一些示例用法:tugberkugurlu.com/archive/…

标签: go package heap priority-queue


【解决方案1】:

这里有你应该首先实现的 heap.Interface。

type Interface interface {
    sort.Interface
    Push(x interface{}) // add x as element Len()
    Pop() interface{}   // remove and return element Len() - 1.
}

这意味着您应该为 PriorityMessage 结构提供必要的方法。将结构实例传递到 heap.Init(&pm) 之后。

您可以在 cmets 中链接的 godoc 中找到详细信息。

只是为了澄清混乱。 Go 是一种缺乏泛型的强类型语言。所以堆包的设计方式是与类型无关的。您可以为要实现的所有类型创建自己的实现。任何类型都实现了 heap.Interface 可以被 heap 包使用。

【讨论】:

    【解决方案2】:
      //https://cs.opensource.google/go/go/+/refs/tags/go1.16.6:src/container/heap/example_intheap_test.go 
        
        // This example demonstrates an integer heap built using the heap interface.
        //package heap_test
        
        import (
            "container/heap"
            "fmt"
        )
        
        // An IntHeap is a min-heap of ints.
        type IntHeap []int
        
        func (h IntHeap) Len() int           { return len(h) }
        func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
        func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
        
        func (h *IntHeap) Push(x interface{}) {
            // Push and Pop use pointer receivers because they modify the slice's length,
            // not just its contents.
            *h = append(*h, x.(int))
        }
        
        func (h *IntHeap) Pop() interface{} {
            old := *h
            n := len(old)
            x := old[n-1]
            *h = old[0 : n-1]
            return x
        }
        
        // This example inserts several ints into an IntHeap, checks the minimum,
        // and removes them in order of priority.
        func Example_intHeap() {
            h := &IntHeap{2, 1, 5}
            heap.Init(h)
            heap.Push(h, 3)
            fmt.Printf("minimum: %d\n", (*h)[0])
            for h.Len() > 0 {
                fmt.Printf("%d ", heap.Pop(h))
            }
            // Output:
            // minimum: 1
            // 1 2 3 5
        }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    相关资源
    最近更新 更多