I have an application (C++) that I think would be well served by an STL priority_queue
. The documentation says:
Priority_queue is a container adaptor, meaning that it is implemented on top of some underlying container type. By default that underlying type is vector, but a different type may be selected explicitly.
and
Priority queues are a standard concept, and can be implemented in many different ways; this implementation uses heaps.
I had previously assumed that top()
is O(1)
, and that push()
would be a O(logn)
(the two reasons I chose the priority_queue
in the first place) - but the documentation neither confirms nor denies this assumption.
Digging deeper, the docs for the Sequence concept say:
The complexities of single-element insert and erase are sequence dependent.
The priority_queue
uses a vector
(by default) as a heap, which:
... supports random access to elements, constant time insertion and removal of elements at the end, and linear time insertion and removal of elements at the beginning or in the middle.
I'm inferring that, using the default priority_queue
, top()
is O(1)
and push()
is O(n)
.
Question 1: Is this correct? (top()
access is O(1)
and push()
is O(n)
?)
Question 2: Would I be able to achieve O(logn)
efficiency on push()
if I used a set
(or multiset
) instead of a vector
for the implementation of the priority_queue
? What would the consequences be of doing this? What other operations would suffer as a consequence?
N.B.: I'm worried about time efficiency here, not space.