我是 Gopher Noob。我最近遇到了這個關于在 Golang 中實作優先級佇列的問題。我通過https://pkg.go.dev/container/[email protected]來實作優先級佇列。所要做的就是為容器實作 heap.Interface 。它足夠簡單,我對此沒有任何疑問。
我的問題是:我需要兩個優先級佇列。一種是最小和最大優先級佇列。在 Java 中,這很容易初始化。我只需要在初始化期間更改比較器就可以了。在 golang 中,我只需要更改sort.Interface 中的Less方法就可以了。但是,我對撰寫冗余代碼不感興趣,我正在尋找更簡潔的方法來創建兩個優先級佇列。
這是我想要做的一個例子:
// A PriorityQueue1
type PriorityQueue1 []*Item
// Implement all the following methods for the min Prioirity queue
func (pq PriorityQueue1) Len() int { return len(pq) }
func (pq PriorityQueue1) 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 PriorityQueue1) Swap(i, j int) {
//Swap
}
func (pq *PriorityQueue1) Push(x interface{}) {
//Define push logic
}
func (pq *PriorityQueue1) Pop() interface{} {
//Define pop logic
}
Now, I define the maximum priority queue (**everything is the same except Less**), which goes like this..
// A PriorityQueue2
type PriorityQueue2 []*Item
// Implement all the following methods for the max Prioirity queue
func (pq PriorityQueue2) Len() int { return len(pq) }
func (pq PriorityQueue2) Less(i, j int) bool {
return **pq[i].priority < pq[j].priority** // Thats it. One line change..
}
func (pq PriorityQueue2) Swap(i, j int) {
//Swap
}
func (pq *PriorityQueue2) Push(x interface{}) {
//Define push logic
}
func (pq *PriorityQueue2) Pop() interface{} {
//Define pop logic
}
現在為什么我必須經歷這種重寫幾乎與最小佇列相同的方法以在 Less 中更改一行的痛苦。我希望減少樣板檔案,我想知道解決這個問題的最簡潔簡潔的方法是什么。我也對使用任何第三方庫不感興趣(但我對它的邏輯感興趣,如果有一個提供干凈的包裝器)。
請提供一些意見。謝謝..
uj5u.com熱心網友回復:
您可以將該函式作為對 Priority Queue 結構的建構式的依賴項注入。
它應該如下作業:
type Item int
type PriorityQueue []Item
var lesser LessFunction
func GetPriorityQueue(l LessFunction) PriorityQueue {
lesser = l
return []Item{}
}
type LessFunction func(i, j int) bool
func (pq PriorityQueue) Less(i, j int) bool {
return lesser(i, j)
}
在代碼中使用它,如下所示:
q := GetPriorityQueue(func(i, j int) bool { return i < j })
請注意:
除了我所展示的方法之外,還有多種方法可以解決這個問題。這顯示了與 Java 的 lambda 函式的相似性。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/371086.html
下一篇:RabbitMQ佇列長度始終為0
