欢迎各位小伙伴来到编程网,相聚于此都是缘哈哈哈!今天我给大家带来《优先级队列返回错误顺序》,这篇文章主要讲到等等知识,如果你对Golang相关的知识非常感兴趣或者正在自学,都可以关注我,我会持续更新相关文章!当然,有什么建议也欢迎在评论留言提出!一起学习!
我编辑了一些关于优先级队列的官方文档,发现了一个有趣的行为:顺序被打乱了。
具体来说,我更新了这一行:
item := heap.pop(&pq).(*item)
使用这一行(现在指向实现的方法本身)
item := pq.pop().(*item)
现在的结果是: 03:香蕉 02:苹果 04:梨
为什么结果不同?如果这两个方法(heap.pop 和 *pq.pop)执行不同的功能,为什么它们的名称相同?它会导致混乱。
package main
import (
"container/heap"
"fmt"
)
// An Item is something we manage in a priority queue.
type Item struct {
value string // The value of the item; arbitrary.
priority int // The priority of the item in the queue.
// The index is needed by update and is maintained by the heap.Interface methods.
index int // The index of the item in the heap.
}
// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue []*Item
func (pq PriorityQueue) Len() int { return len(pq) }
func (pq PriorityQueue) Less(i, j int) bool {
// We want Pop to give us the highest, not lowest, priority so we use greater than here.
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]
old[n-1] = nil // avoid memory leak
item.index = -1 // for safety
*pq = old[0 : n-1]
return item
}
// update modifies the priority and value of an Item in the queue.
func (pq *PriorityQueue) update(item *Item, value string, priority int) {
item.value = value
item.priority = priority
heap.Fix(pq, item.index)
}
// This example creates a PriorityQueue with some items, adds and manipulates an item,
// and then removes the items in priority order.
func main() {
// Some items and their priorities.
items := map[string]int{
"banana": 3, "apple": 2, "pear": 4,
}
// Create a priority queue, put the items in it, and
// establish the priority queue (heap) invariants.
pq := make(PriorityQueue, len(items))
i := 0
for value, priority := range items {
pq[i] = &Item{
value: value,
priority: priority,
index: i,
}
i++
}
heap.Init(&pq)
// Take the items out; they arrive in decreasing priority order.
for pq.Len() > 0 {
//item := heap.Pop(&pq).(*Item)
item := pq.Pop().(*Item)
fmt.Printf("%.2d:%s ", item.priority, item.value)
}
}
正确答案
如果你仔细观察,priorityqueue
实际上只是一个[]*item
。文档中定义 // priorityqueue实现heap.interface并保存items
。这个堆接口定义在documentation中:
// Note that Push and Pop in this interface are for package heap's
// implementation to call. To add and remove things from the heap,
// use heap.Push and heap.Pop.
type Interface interface {
sort.Interface
Push(x interface{}) // add x as element Len()
Pop() interface{} // remove and return element Len() - 1.
}
很明显,优先级队列使用堆来正常工作。 heap 有 push 和 pop 方法,然后使用 priorityqueue 定义的方法对队列中的 item 进行排序、存储和优先级。
您所做的只是显示您存储的列表。在此过程中没有发生排序和优先级。
以上就是《优先级队列返回错误顺序》的详细内容,更多关于的资料请关注编程网公众号!