1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
pqueue.go 1.53 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2022-10-22 01:06 . rpc ,排序权重
package queue
import "container/heap"
type PQueue []IPriorityItem
var _ Queue = (*PQueue)(nil)
// Len returns the PQueue length.
func (pq PQueue) Len() int { return len(pq) }
// Less 权重越少越大前面
func (pq PQueue) Less(i, j int) bool {
in := pq[i]
jn := pq[j]
if in == nil || jn == nil {
return false
}
return in.PValue() < jn.PValue()
}
// Swap exchanges the indexes of the items.
func (pq PQueue) Swap(i, j int) {
temp := pq[i]
pq[i] = pq[j]
pq[j] = temp
}
func (pq *PQueue) Add(elem interface{}) error {
heap.Push(pq, elem)
return nil
}
// Push implements the heap.Interface.Push.
// Adds x as element Len().
func (pq *PQueue) Push(x interface{}) {
*pq = append(*pq, ConvertPriorityItem(x))
}
// Pop implements the heap.Interface.Pop.
// Removes and returns element Len() - 1.
func (pq *PQueue) Pop() interface{} {
old := *pq
item := old[0]
*pq = old[1:]
return item.GValue()
}
// Head returns the first item of a PQueue without removing it.
func (pq *PQueue) Head() IPriorityItem {
if pq.Empty() {
return nil
}
return (*pq)[0]
}
func (pq *PQueue) Peek() interface{} {
if pq.Empty() {
return nil
}
return (*pq)[0].GValue()
}
// Remove removes and returns the element at index i from the PQueue.
func (pq *PQueue) Remove(i int) interface{} {
return heap.Remove(pq, i)
}
func (pq *PQueue) Empty() bool {
return pq.Len() == 0
}
// Find return index -1 not found.
func (pq *PQueue) Find(fn IndexFunc) (interface{}, int) {
for i := range *pq {
if fn((*pq)[i], i) {
return (*pq)[i], i
}
}
return nil, -1
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.3.25

搜索帮助