Why is a vector used while defining priority queue of structures?

Viewed 878

I know that we can define a priority queue of structures in the following way -

std::priority_queue<somestructure, vector<somestructure>, compare> pq;

Where compare is the structure which contains the compare function. I want to ask why we need to use vector as the second argument in this declaration. How is a vector related to a priority queue while defining the above priority queue?

1 Answers

std::priority_queue is what we call a container adapter. As you know in C++ we got containers like std::vector, std:array or std::deque. All those are there to directly save stuff of type T into them, with different pros and cons.

std::stack for example is a container adapter, which can be used on top of std:deque. The only thing this adapter does is to take away the functionality of std::deque to insert at the end, or take from the end. By this the user is forced to use the std::deque only like a stack.

Something similiar is true for std::priority_queue, it forces you to only insert into the underlying container, a std::vector for example, in an order. By this you get some nice properties of how to find elements in this container. In this special case, by taking more effort into how to insert new elements in the underlying container, and taking away the freedom to randomly insert an element anywhere you like. So you got O(log(n)) complexity for the insert instead of O(1) (instead of inserting at the end for example). But by that you have a complexity of only O(1) to find the largest element, instead of O(n).

There is nothing special about std::vector in this case, you could use any container that satisfy the needs of this container adaptor, you could also use std::deque or your own container or to quote:

The type of the underlying container to use to store the elements. The container must satisfy the requirements of SequenceContainer, and its iterators must satisfy the requirements of LegacyRandomAccessIterator. Additionally, it must provide the following functions with the usual semantics: front() push_back() pop_back() The standard containers std::vector and std::deque satisfy these requirements.

Related