Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
Golang containerHeap堆操作使用示例_创想鸟

Golang containerHeap堆操作使用示例

Go语言中container/heap需实现heap.Interface接口,通过定义Len、Less、Swap、Push、Pop方法构建最小堆或优先队列,如IntHeap或TaskHeap,使用heap.Init初始化后可进行堆操作。

golang containerheap堆操作使用示例

在 Go 语言中,container/heap 包提供了对堆数据结构的支持,但并没有直接提供一个开箱即用的“Heap”类型。你需要基于 heap.Interface 接口实现自己的堆类型,通常结合切片(slice)来完成。下面是一个使用 container/heap 构建最小堆的操作示例,适用于整数或自定义结构体。

定义一个最小堆结构体

我们通过定义一个包含 int 切片的类型,并实现 heap.Interface 的五个方法:Len、Less、Swap、Push 和 Pop。

type IntHeap []int// Len, Less, Swap 是 slice 的基本操作func (h IntHeap) Len() int           { return len(h) }func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] } // 最小堆:小于号func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }// Push 和 Pop 是 heap 包调用的方法,注意接收者是指针func (h *IntHeap) Push(x interface{}) {    *h = append(*h, x.(int))}func (h *IntHeap) Pop() interface{} {    old := *h    n := len(old)    x := old[n-1]    *h = old[0 : n-1]    return x}

初始化并使用堆

使用 heap.Init 初始化一个切片,然后进行插入、删除等操作。

package mainimport (    "container/heap"    "fmt")func main() {    // 创建并初始化堆    h := &IntHeap{3, 1, 4, 1, 5}    heap.Init(h)    // 插入元素    heap.Push(h, 2)    heap.Push(h, 6)    // 弹出最小元素    for h.Len() > 0 {        min := heap.Pop(h).(int)        fmt.Print(min, " ") // 输出: 1 1 2 3 4 5 6    }    fmt.Println()}

扩展:优先队列(含权重的任务)

实际开发中,堆常用于实现优先队列。以下是一个带优先级的任务示例:

立即学习“go语言免费学习笔记(深入)”;

type Task struct {    Name     string    Priority int // 数值越小,优先级越高}type TaskHeap []Taskfunc (th TaskHeap) Len() int            { return len(th) }func (th TaskHeap) Less(i, j int) bool  { return th[i].Priority  0 {        t := heap.Pop(tasks).(Task)        fmt.Printf("Execute: %s (Priority: %d)n", t.Name, t.Priority)    }}

基本上就这些。只要实现 heap.Interface 的方法,你就能自由地构建最大堆、最小堆或任意排序规则的优先队列。注意 Push 和 Pop 必须定义在指针类型上,因为它们会修改切片本身。不复杂但容易忽略细节。

以上就是Golang containerHeap堆操作使用示例的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1410234.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
如何在Golang中实现WebSocket多客户端通信
上一篇 2025年12月16日 03:09:54
使用 Go 语言检测进程是否存在
下一篇 2025年12月16日 03:10:02

相关推荐

发表回复

登录后才能评论
关注微信