go - 为什么交换成员函数不需要使用指针?
问题描述
我是 Golang 的新手。当我尝试实现我的第一个 PriorityQueue 时,我发现 Push 和 Pop 函数需要使用成员的指针,而 Swap 不需要。
我知道如果您在成员函数中使用指针,这意味着您可以更改实例本身而不是其副本。但是为什么 Swap 可以使用副本而不是指针呢?
type maxHeap []int
func (max maxHeap) Len() int {
return len(max)
}
func (max maxHeap) Less(a, b int) bool {
return max[a] > max[b]
}
func (max maxHeap) Swap(a, b int) {
max[a], max[b] = max[b], max[a]
}
func (max *maxHeap) Push(a interface{}) {
*max = append(*max, a.(int))
}
func (max *maxHeap) Pop() interface{} {
x := (*max)[len(*max)-1]
*max = (*max)[0 : len(*max)-1]
return x
}
解决方案
Try this as an exercise: write all the functions using a pointer receiver. In each function, grab the current value of the pointer at the top, to use until you need to change the value stored through the pointer.
So Swap
and Push
, respectively, become:
func (p *maxHeap) Swap(a, b int) {
max := *p
max[a], max[b] = max[b], max[a]
}
func (p *maxHeap) Push(a interface{}) {
max := *p
*p = append(max, a.(int))
}
Repeat for the other functions as needed.
Now, go back through each converted function. Which ones assign a new value to *p
? Which functions never assign a new value and just keep using max
?
When you answer this question, you should find yourself enlightened.
Side note: since Push
immediately converts a
to int
, it probably should just take int
. Likewise, Pop
should just return int
. Alternatively, well, see the standard container/heap
package.
推荐阅读
- html - 创建一个空的div来放置边框
- java - 找到 IPCM 宏块
- angular - 使用 .NET core 2 为 Angular 6 启用 SSR
- javascript - 更改高图中平行轴之间的默认距离
- node.js - nodejs 批量更新而不影响性能
- c - 在 C 中的 scanf() 之后转到上一行
- javascript - 检测是否在 Google Customer Reviews Popup 中选择了 Yes
- r - 在 R 中下载 Keras resnet50 模型时遇到问题
- vb.net - 如何访问动态加载的用户控件 vb.net 的方法
- c# - 当前上下文中不存在变量