组合Golang container包中的vector和heap,可以实现一个heap算法的队列。Vector实现了interface{}接口,可以放置任意的struct元素,只要该元素实现了vector.LessInterface就可以通过heap排序了。如:
type elem struct { idx int64 name string } func (p *elem) Less(y interface{}) bool { return p.idx < y.(*elem).idx }
这样elem的元素就可以通过heap算法,有序地从Vector中Push或Pop了。完整代码如下:
package main import ( "container/heap" "container/vector" "fmt" ) type elem struct { idx int64 name string } func (p *elem) Less(y interface{}) bool { return p.idx < y.(*elem).idx } func test() { v := &vector.Vector{} heap.Init(v) heap.Push(v, &elem{10, "test10"}) heap.Push(v, &elem{100, "test100"}) heap.Push(v, &elem{9, "test9"}) for i:=0; i < 3; i++ { fmt.Println(heap.Pop(v).(*elem).name) } } func main() { test() }