douken1726 2015-06-14 09:17
浏览 84

Go是否具有开箱即用的优先级队列?

Does Go has out of the box priority queue (the one that I can just import from some module and start using like python's priority queue)?

I know that priority queues are often implemented using heap data structure and go has a heap package, which also suggests how to use it to implement a queue (in Example (PriorityQueue) ), which I can easily grab and use.

My question is this a recommended way to do this, or there is an out of the box Priority Queue package that I failed to find?

  • 写回答

1条回答 默认 最新

  • dongre8505 2015-06-14 11:19
    关注

    Quoting Wikipedia:

    a priority queue is an abstract data type which is like a regular queue or stack data structure, but where additionally each element has a "priority" associated with it. [...] While priority queues are often implemented with heaps, they are conceptually distinct from heaps. A priority queue is an abstract concept like "a list" or "a map";

    Go provides some basic data structures that are used in most applications but leave the implementation of more specialized data structures to the programmer. For example, the go map can be used to trivially implement a set.

    The example you link to uses a slice []*Item to represent the more abstract type heap.Interface and also the (even more abstract) type PriorityQueue. Go is about composition and I would say that implementing PriorityQueue in terms of heap operations is good practice.

    This gives you control as a programmer. If you want thread safety, use the composition of PriorityQueue and sync.Mutex to make it thread safe. If you want a different implementation than a heap, make PriorityQueue an interface and you can implement it however you want.

    Of course there's a trade-off. In this case, the implementation was ~25 lines of code. If the implementation was hundreds of lines you'd probably want to find a package that has done this already.

    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)