Efficiency of the STL priority_queue

前端 未结 6 1213
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 06:11

I have an application (C++) that I think would be well served by an STL priority_queue. The documentation says:

Priority_queue is a cont

6条回答
  •  北荒
    北荒 (楼主)
    2020-11-30 07:00

    If the underlying data structure is a heap, top() will be constant time, and push (EDIT: and pop) will be logarithmic (like you are saying). The vector is just used to store these things like this:

    HEAP:
                 1
            2         3
          8 12   11 9

    VECTOR (used to store)

    1 2 3 8 12 11 9

    You can think of it as the element at position i's children is (2i) and (2i+1)

    They use the vector because it stores the data sequentially (which is much more efficient and cache-friendly than discrete)

    Regardless of how it is stored, a heap should always be implemented (especially by the gods who made the STD lib) so that pop is constant and push is logarithmic

提交回复
热议问题