前言
在 Go 语言的 container/heap
包中,heap.Pop()
方法并不保证对于同优先级的元素会遵循先进先出(FIFO)的顺序。堆的主要特性是根据优先级来组织元素,而不是根据插入顺序。
实现先进先出的堆
如果在处理同优先级元素时能够保持先进先出的顺序,你可以在堆的实现中引入一个额外的字段来记录插入顺序。例如,可以为每个元素添加一个索引或时间戳,并在 Less
方法中首先比较优先级,如果优先级相同,则比较插入顺序。
以下是一个示例,演示如何实现一个支持同优先级元素先进先出的堆:
package main
import (
"container/heap"
"fmt"
)
type Item struct {
value string // The value of the item
priority int // The priority of the item
index int // The index of the item in the heap
}
type PriorityQueue []*Item
func (pq PriorityQueue) Len() int {
return len(pq)
}
func (pq PriorityQueue) Less(i, j int) bool {
// 首先比较优先级,如果相同则比较插入顺序
if pq[i].priority == pq[j].priority {
return pq[i].index < pq[j].index // 保证先进先出
}
return pq[i].priority < pq[j].priority
}
func (pq PriorityQueue) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
pq[i].index = i
pq[j].index = j
}
func (pq *PriorityQueue) Push(x interface{}) {
n := len(*pq)
item := x.(*Item)
item.index = n
*pq = append(*pq, item)
}
func (pq *PriorityQueue) Pop() interface{} {
old := *pq
n := len(old)
item := old[n-1]
*pq = old[0 : n-1]
return item
}
func main() {
pq := &PriorityQueue{}
heap.Init(pq)
heap.Push(pq, &Item{value: "task1", priority: 2})
heap.Push(pq, &Item{value: "task2", priority: 1})
heap.Push(pq, &Item{value: "task3", priority: 2})
for pq.Len() > 0 {
item := heap.Pop(pq).(*Item)
fmt.Printf("%s (priority: %d)\n", item.value, item.priority)
}
}