Since both std::priority_queue
and std::set
(and std::multiset
) are data containers that store elements and allow you to access them in an ordered fashion, and have same insertion complexity O(log n)
, what are the advantages of using one over the other (or, what kind of situations call for the one or the other?)?
While I know that the underlying structures are different, I am not as much interested in the difference in their implementation as I am in the comparison their performance and suitability for various uses.
Note: I know about the no-duplicates in a set. That's why I also mentioned std::multiset
since it has the exactly same behavior as the std::set
but can be used where the data stored is allowed to compare as equal elements. So please, don't comment on single/multiple keys issue.
std::priority_queue A priority queue is a container adaptor that provides constant time lookup of the largest (by default) element, at the expense of logarithmic insertion and extraction.
Or you can use greater as mentioned here. Here is the diff from your TLE code. PS - priority queue is 30 times faster than set.
In use, multiset seems more versatile than priority queue due to the fact that you can remove things other than the first element.
A priority queue only gives you access to one element in sorted order -- i.e., you can get the highest priority item, and when you remove that, you can get the next highest priority, and so on. A priority queue also allows duplicate elements, so it's more like a multiset than a set. [Edit: As @Tadeusz Kopec pointed out, building a heap is also linear on the number of items in the heap, where building a set is O(N log N) unless it's being built from a sequence that's already ordered (in which case it is also linear).]
A set allows you full access in sorted order, so you can, for example, find two elements somewhere in the middle of the set, then traverse in order from one to the other.
std::priority_queue
allows to do the following:
O(log n)
O(1)
O(log n)
while std::set
has more possibilities:
O(log n)
and the constant is greater than in std::priority_queue
O(log n)
O(log n)
(lower_bound
)O(log n)
iterator
O(1)
O(1)
O(1)
O(1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With