容器

来解释一下什么是容器,通俗的将容器就是存放一堆数据的内存块,今天我们手动实现一个堆.

下面的方法应该比较熟悉

heap.Interface 接口

func Fix(h Interface, i int)
func Init(h Interface)
func Pop(h Interface) interface{}
func Push(h Interface, x interface{})
func Remove(h Interface, i int) interface{}
type Interface

这是一般数组都具有的能力,下面我们实现一下

// 本示例演示了使用堆接口构建的整数堆。
package main

import (
  "container/heap"
  "fmt"
)

// IntHeap是一个整型的整数。
type IntHeap []int

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] }

func (h *IntHeap) Push(x interface{}) {
  // Push和Pop使用指针接收器,因为它们修改切片的长度,
  // 不仅仅是其内容。
  *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
}

// 本示例将几个int插入到IntHeap中,检查最小值,
// 并按优先顺序删除它们。
func main() {
  h := &IntHeap{2, 1, 5}
  heap.Init(h)
  heap.Push(h, 3)
  fmt.Printf("minimum: %d\n", (*h)[0])
  for h.Len() > 0 {
    fmt.Printf("%d ", heap.Pop(h))
  }

heap 是什么?

Heap 包为任何实现 heap.Interface 的类型提供堆操作。堆是具有属性的树,每个节点是其子树中的最小值节点

如果你的对象实现了这个接口的方法,你就可以调用heap提供的方法进行数据操作

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值