我正在嘗試根據(jù)文檔中提供的示例實現(xiàn)優(yōu)先級隊列。文檔:priorityQueue簡而言之,它看起來像這樣(并非所有內(nèi)容都包括在內(nèi)): package pq type Item struct { container interface{} priority int index int } type PriorityQueue []*Item func NewItem(value interface{}, prio int) *Item { return &Item {container: value, priority: prio} }func (pq PriorityQueue) Len() int { return len(pq)}func (pq PriorityQueue) Less(i, j int) bool { 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{}) { fmt.Printf("adr: %p\n", &pq) n := len(pq) item := x.(*Item) item.index = n pq = append(pq, item) }func (pq *PriorityQueue) Pop() interface{} { old := *pq n := len(old) itm := old[n - 1] itm.index = -1 *pq = old[0 : n-1] return itm.container}該main.go文件:func main() { q := pq.PriorityQueue{} heap.Init(q) fmt.Printf("\nAdr: %p\n", &q) q.Push(pq.NewItem("h", 2)) for i := 0; i < 5; i++ { item := pq.NewItem("test", i * 13 % 7) heap.Push(q, item) } for q.Len() > 0 { fmt.Println("Item: " + heap.Pop(q).(string)) }}正如您在與示例進行比較時所看到的,我不使用指針,因為這樣做會給我一個編譯錯誤,告訴我我的優(yōu)先級隊列沒有正確實現(xiàn)接口。當我這樣做時,這給我留下了以下問題:heap.Push(q, item)該項目未附加到隊列中。我試圖寫出隊列指針地址,它顯示了不同的地址。這解釋了為什么它不起作用,但是切片不是很長的地圖引用類型嗎?更具體地說:我如何解決我的問題?希望你能幫上忙!編輯:添加完整代碼和錯誤:不能使用 q(類型 pq.PriorityQueue)作為類型 heap.Interface 在函數(shù)參數(shù)中:pq.PriorityQueue 沒有實現(xiàn) heap.Interface(Pop 方法有指針接收器)
- 1 回答
- 0 關注
- 230 瀏覽
添加回答
舉報
0/150
提交
取消