Difference between std::set and std::priority_queue

前端 未结 4 1665
情书的邮戳
情书的邮戳 2021-01-29 23:14

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

4条回答
  •  闹比i
    闹比i (楼主)
    2021-01-29 23:51

    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?)?

    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.

提交回复
热议问题