重写Pop()方法

huangapple go评论75阅读模式
英文:

Re-write of the Pop() method

问题

在Go的安装中,它们在container/heap/example_pq_test.go中提供了一个优先队列的示例。我将整个文件的内容粘贴在这里,以便我可以询问关于Pop()方法的问题。

// 版权所有 2012 年 Go 作者。版权所有。
// 此源代码的使用受 BSD 风格的许可证管辖,该许可证可以在 LICENSE 文件中找到。

// 此示例演示了使用堆接口构建的优先队列。
package heap_test

import (
	"container/heap"
	"fmt"
)

// Item 是我们在优先队列中管理的东西。
type Item struct {
	value    string // 项目的值;任意值。
	priority int    // 项目在队列中的优先级。
	// 索引由 update 方法所需,并由 heap.Interface 方法维护。
	index int // 项目在堆中的索引。
}

// PriorityQueue 实现了 heap.Interface 并保存 Items。
type PriorityQueue []*Item

func (pq PriorityQueue) Len() int { return len(pq) }

func (pq PriorityQueue) Less(i, j int) bool {
	// 我们希望 Pop 给我们最高的优先级,所以我们在这里使用大于号。
	return pq[i].priority > pq[j].priority
}

func (pq PriorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

func (pq *PriorityQueue) Push(x interface{}) {
	n := len(*pq)
	item := x.(*Item)
	item.index = n
	*pq = append(*pq, item)
}

func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	old[n-1] = nil  // 避免内存泄漏
	item.index = -1 // 为了安全起见
	*pq = old[0 : n-1]
	return item
}

// update 修改队列中项目的优先级和值。
func (pq *PriorityQueue) update(item *Item, value string, priority int) {
	item.value = value
	item.priority = priority
	heap.Fix(pq, item.index)
}

// 此示例创建一个带有一些项目的 PriorityQueue,添加和操作一个项目,
// 然后按优先级顺序删除项目。
func Example_priorityQueue() {
	// 一些项目及其优先级。
	items := map[string]int{
		"banana": 3, "apple": 2, "pear": 4,
	}

	// 创建一个优先队列,将项目放入其中,
	// 并建立优先队列(堆)的不变性。
	pq := make(PriorityQueue, len(items))
	i := 0
	for value, priority := range items {
		pq[i] = &Item{
			value:    value,
			priority: priority,
			index:    i,
		}
		i++
	}
	heap.Init(&pq)

	// 插入一个新项目,然后修改其优先级。
	item := &Item{
		value:    "orange",
		priority: 1,
	}
	heap.Push(&pq, item)
	pq.update(item, item.value, 5)

	// 取出项目;它们按降序到达。
	for pq.Len() > 0 {
		item := heap.Pop(&pq).(*Item)
		fmt.Printf("%.2d:%s ", item.priority, item.value)
	}
	// 输出:
	// 05:orange 04:pear 03:banana 02:apple
}

如果我将Pop()方法修改为以下内容(不创建原始切片的深拷贝),可能会带来什么危害或错误?

func (pq *PriorityQueue) Pop2() interface{} {
	n := len(*pq)
	item := (*pq)[n-1]
	(*pq)[n-1] = nil  // 避免内存泄漏
	item.index = -1 // 为了安全起见
	*pq = (*pq)[:n-1]
	return item
}

我相信在原始的Pop()方法中,这一行创建了一个深拷贝(分配了一个新的底层数组)用于切片old := *pq。这是正确的吗?

英文:

Under Go's installation, they have an example of priority queue at container/heap/example_pq_test.go
I am pasting the contents of the entire file so that I can ask about the Pop() method.

// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This example demonstrates a priority queue built using the heap interface.
package heap_test
import (
"container/heap"
"fmt"
)
// An Item is something we manage in a priority queue.
type Item struct {
value    string // The value of the item; arbitrary.
priority int    // The priority of the item in the queue.
// The index is needed by update and is maintained by the heap.Interface methods.
index int // The index of the item in the heap.
}
// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue []*Item
func (pq PriorityQueue) Len() int { return len(pq) }
func (pq PriorityQueue) 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 PriorityQueue) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
pq[i].index = i
pq[j].index = j
}
func (pq *PriorityQueue) Push(x any) {
n := len(*pq)
item := x.(*Item)
item.index = n
*pq = append(*pq, item)
}
func (pq *PriorityQueue) Pop() any {
old := *pq
n := len(old)
item := old[n-1]
old[n-1] = nil  // avoid memory leak
item.index = -1 // for safety
*pq = old[0 : n-1]
return item
}
// update modifies the priority and value of an Item in the queue.
func (pq *PriorityQueue) update(item *Item, value string, priority int) {
item.value = value
item.priority = priority
heap.Fix(pq, item.index)
}
// This example creates a PriorityQueue with some items, adds and manipulates an item,
// and then removes the items in priority order.
func Example_priorityQueue() {
// Some items and their priorities.
items := map[string]int{
"banana": 3, "apple": 2, "pear": 4,
}
// Create a priority queue, put the items in it, and
// establish the priority queue (heap) invariants.
pq := make(PriorityQueue, len(items))
i := 0
for value, priority := range items {
pq[i] = &Item{
value:    value,
priority: priority,
index:    i,
}
i++
}
heap.Init(&pq)
// Insert a new item and then modify its priority.
item := &Item{
value:    "orange",
priority: 1,
}
heap.Push(&pq, item)
pq.update(item, item.value, 5)
// Take the items out; they arrive in decreasing priority order.
for pq.Len() > 0 {
item := heap.Pop(&pq).(*Item)
fmt.Printf("%.2d:%s ", item.priority, item.value)
}
// Output:
// 05:orange 04:pear 03:banana 02:apple
}

What harm may come or is there a fallacy if I had the Pop() method as below(without creating a deep copy of the original slice)

func (pq *PriorityQueue) Pop2() any {
n := len(*pq)
item := (*pq)[n-1]
(*pq)[n-1] = nil  // avoid memory leak
item.index = -1 // for safety
*pq = (*pq)[: n-1]
return item
}

I believe in the original Pop() method, this line creates a deep copy(allocates a new underlying array) for the slice old := *pq. Is that true?

答案1

得分: 2

make函数创建的对象,比如mapslice,更像是指向数据位置的指针,而不是数据本身。

So old := *pq 的行为更像是别名,而不是数据的复制。

英文:

The objects created by the make function, here map and slice, are more like pointers pointing to the location of the data than the data itself.

So old := *pq behaves more like an Alias than data copy.

huangapple
  • 本文由 发表于 2023年6月30日 07:21:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76585126.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定