Difference between std::set and std::priority_queue

前端 未结 4 1730
情书的邮戳
情书的邮戳 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
    2021-01-29 23:58

    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.

提交回复
热议问题