The documentation for std::priority_queue
states the complexity of the push
operation as:
Logarithmic number of comparisons plus the complexity of
Container::push_back
.
And by default uses std::vector
as the underlying container. However, push_back
can only push elements to the end of the vector, while in a priority queue one might need to add elements somewhere in the middle of the vector, in which case all elements that follow have to be shifted to the right. In the worst case, when adding an element at the beginning, the push operation would incur the full O(n) cost. So how does the priority queue do it in logarithmic time? Why does it use a vector by default as opposed to some "easy insert and find" container such as a heap?