← 中文资源

简体中文版本

用 IntHeap 管理优先级队列

在 int 切片上实现 container/heap 的 Interface 五方法:Init 建堆、Push 插入、Pop 按优先级弹出,最小堆语义下取值天然有序,无需手动排序。

阅读英文原文

实现说明

除了函数 Len、Less、Swap、Push,文件里再无其他定义。 for h.Len() > 0 是唯一的迭代点——其余代码顺序执行一遍。

使用要点

  • 演示输出是带标签的(pop order:),每个操作都会留下自己的一行标注。
  • main 的演示流程是 Push、Len、Pop——跑一遍文件,这条流程从头到尾可见。

常见问题

运行「用 IntHeap 管理优先级队列」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 pop order: 这类标签。

入口签名:func (h IntHeap) Len() int

核心语句

func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] } // priority queue: smaller first
func (h *IntHeap) Push(x any) { *h = append(*h, x.(int)) }
func (h IntHeap) Len() int           { return len(h) }

代码示例

package main

import (
	"container/heap"
	"fmt"
)

// IntHeap 实现 heap.Interface:最小堆,pop 顺序即优先级顺序
type IntHeap []int

func (h IntHeap) Len() int           { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] } // priority queue: smaller first
func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *IntHeap) Push(x any) { *h = append(*h, x.(int)) }
func (h *IntHeap) Pop() any {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[:n-1]
	return x
}

func main() {
	h := &IntHeap{5, 1, 3}
	heap.Init(h) // 建堆:O(n)
	heap.Push(h, 2)
	heap.Push(h, 0)

	fmt.Println("pop order:")
	for h.Len() > 0 {
		fmt.Print(heap.Pop(h), " ")
	}
	fmt.Println()
}