HUH函數(shù)
2022-10-17 15:46:26
我是一個(gè)地鼠菜鳥。我最近遇到了關(guān)于在 Golang 中實(shí)現(xiàn)優(yōu)先級(jí)隊(duì)列的問題。我通過https://pkg.go.dev/container/heap@go1.17.3實(shí)現(xiàn)了優(yōu)先級(jí)隊(duì)列。只需為容器實(shí)現(xiàn) heap.Interface 即可。它很簡(jiǎn)單,我對(duì)此沒有任何疑問。不過我的問題是:我需要兩個(gè)優(yōu)先級(jí)隊(duì)列。一種是最小和最大優(yōu)先級(jí)隊(duì)列。在 Java 中,這很容易被初始化。我只需要在初始化期間更改比較器即可。在 golang 中,我只需要更改 sort.Interface 中的Less方法就可以了。但是,我對(duì)編寫冗余代碼不感興趣,我正在尋找更簡(jiǎn)潔的方法來創(chuàng)建兩個(gè)優(yōu)先級(jí)隊(duì)列。這是我想要做的一個(gè)例子:// 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}現(xiàn)在為什么我必須經(jīng)歷這種重寫幾乎與最小隊(duì)列相同的方法的考驗(yàn),以便在 Less 中進(jìn)行單行更改。我希望減少樣板文件,我想知道解決這個(gè)問題的最簡(jiǎn)潔明了的方法是什么。我也對(duì)使用任何第三方庫不感興趣(但我對(duì)它的邏輯感興趣,如果有一個(gè)提供干凈的包裝器)。請(qǐng)?zhí)峁┮恍┹斎?。謝謝..
1 回答

慕絲7291255
TA貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個(gè)贊
您可以將該函數(shù)作為依賴項(xiàng)注入到 Priority Queue 結(jié)構(gòu)的構(gòu)造函數(shù)中。
它應(yīng)該按如下方式工作:
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 })
請(qǐng)注意:
除了我所展示的之外,還有多種方法可以解決這個(gè)問題。這顯示了與 Java 的 lambda 函數(shù)的相似性。
- 1 回答
- 0 關(guān)注
- 116 瀏覽
添加回答
舉報(bào)
0/150
提交
取消