我是一个地鼠菜鸟。我最近遇到了关于在 Golang 中实现优先级队列的问题。我通过https://pkg.go.dev/container/heap@go1.17.3实现了优先级队列。只需为容器实现 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 关注
- 102 浏览
添加回答
举报
0/150
提交
取消