我是一個地鼠菜鳥。我最近遇到了關于在 Golang 中實現優先級隊列的問題。我通過https://pkg.go.dev/container/[email protected]實現了優先級隊列。只需為容器實現 heap.Interface 即可。它很簡單,我對此沒有任何疑問。不過我的問題是:我需要兩個優先級隊列。一種是最小和最大優先級隊列。在 Java 中,這很容易被初始化。我只需要在初始化期間更改比較器即可。在 golang 中,我只需要更改 sort.Interface 中的Less方法就可以了。但是,我對編寫冗余代碼不感興趣,我正在尋找更簡潔的方法來創建兩個優先級隊列。這是我想要做的一個例子:// A PriorityQueue1type PriorityQueue1 []*Item// Implement all the following methods for the min Prioirity queuefunc (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 PriorityQueue2type PriorityQueue2 []*Item// Implement all the following methods for the max Prioirity queuefunc (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 中進行單行更改。我希望減少樣板文件,我想知道解決這個問題的最簡潔明了的方法是什么。我也對使用任何第三方庫不感興趣(但我對它的邏輯感興趣,如果有一個提供干凈的包裝器)。請提供一些輸入。謝謝..
1 回答
慕絲7291255
TA貢獻1859條經驗 獲得超6個贊
您可以將該函數作為依賴項注入到 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 函數的相似性。
- 1 回答
- 0 關注
- 121 瀏覽
添加回答
舉報
0/150
提交
取消
