关于 go 的优先队列问题,这里大佬多,帮忙看看

18次阅读

共计 579 个字符,预计需要花费 2 分钟才能阅读完成。

优先队列中:

需要定义 Pop() 函数,Pop 函数定义的时候,明明是把队尾的元素(列表是从小到大排序,队尾即为最大值)删除,但是效果却是把队首(最小值)删除?

源码位置:

https://github.com/golang/go/blob/6076edc55c548878c261316f3e3294f1f73125a3/src/container/heap/example_intheap_test.go#L26

看这里明明是把队列的尾元素去除

func (h *IntHeap) Pop() any {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

打印的效果:

Pop 的时候竟然是最小的先出来??

// 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: %dn", (*h)[0])
	for h.Len()> 0 {fmt.Printf("%d", heap.Pop(h))
	}
	// Output:
	// minimum: 1
	// 1 2 3 5
}
正文完
 0