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
Since both
std::priority_queue
andstd::set
(andstd::multiset
) are data containers that store elements and allow you to access them in an ordered fashion, and have same insertion complexityO(log n)
, what are the advantages of using one over the other (or, what kind of situations call for the one or the other?)?
Even though insert and erase operations for both containers have the same complexity O(log n), these operations for std::set
are slower than for std::priority_queue
. That's because std::set
makes many memory allocations. Every element of std::set
is stored at its own allocation. std::priority_queue
(with underlying std::vector
container by default) uses single allocation to store all elements. On other hand std::priority_queue
uses many swap operations on its elements whereas std::set
uses just pointers swapping. So if swapping is very slow operation for element type, using std::set
may be more efficient. Moreover element may be non-swappable at all.
Memory overhead for std::set
is much bigger also because it has to store many pointers between its nodes.