实现说明
真正干活的是函数 Len、Less、Swap、Push,其余都是接线。
驱动整个流程的是 for h.Len() > 0 这一个循环。
使用要点
- 运行整个文件:
main会依次驱动Push、Len、Pop。
常见问题
「基于 container/heap 的泛型最小堆」这个示例怎么运行?
文件自包含:直接运行,没有需要预先安装的依赖。
签名一览:func (h Heap[T]) Len() int
核心语句
func (h Heap[T]) Less(i, j int) bool { return h.data[i] < h.data[j] }
func (h *Heap[T]) Push(v any) { h.data = append(h.data, v.(T)) }
func (h Heap[T]) Len() int { return len(h.data) }
代码示例
package main
import (
"cmp"
"container/heap"
"fmt"
)
// Heap adapts any cmp.Ordered type into a generic min-heap:
// smallest value pops first
type Heap[T cmp.Ordered] struct {
data []T
}
func (h Heap[T]) Len() int { return len(h.data) }
func (h Heap[T]) Less(i, j int) bool { return h.data[i] < h.data[j] }
func (h Heap[T]) Swap(i, j int) { h.data[i], h.data[j] = h.data[j], h.data[i] }
func (h *Heap[T]) Push(v any) { h.data = append(h.data, v.(T)) }
func (h *Heap[T]) Pop() any {
old := h.data
n := len(old)
v := old[n-1]
h.data = old[:n-1]
return v
}
func main() {
h := &Heap[string]{data: []string{"pear", "apple", "fig"}}
heap.Init(h)
heap.Push(h, "date")
for h.Len() > 0 {
fmt.Println(heap.Pop(h))
}
}