Difference between std::set and std::priority_queue

前端 未结 4 1664
情书的邮戳
情书的邮戳 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条回答
  •  一生所求
    2021-01-29 23:54

    set/multiset are generally backed by a binary tree. http://en.wikipedia.org/wiki/Binary_tree

    priority_queue is generally backed by a heap. http://en.wikipedia.org/wiki/Heap_(data_structure)

    So the question is really when should you use a binary tree instead of a heap?

    Both structures are laid out in a tree, however the rules about the relationship between anscestors are different.

    We will call the positions P for parent, L for left child, and R for right child.

    In a binary tree L < P < R.

    In a heap P < L and P < R

    So binary trees sort "sideways" and heaps sort "upwards".

    So if we look at this as a triangle than in the binary tree L,P,R are completely sorted, whereas in the heap the relationship between L and R is unknown (only their relationship to P).

    This has the following effects:

    • If you have an unsorted array and want to turn it into a binary tree it takes O(nlogn) time. If you want to turn it into a heap it only takes O(n) time, (as it just compares to find the extreme element)

    • Heaps are more efficient if you only need the extreme element (lowest or highest by some comparison function). Heaps only do the comparisons (lazily) necessary to determine the extreme element.

    • Binary trees perform the comparisons necessary to order the entire collection, and keep the entire collection sorted all-the-time.

    • Heaps have constant-time lookup (peek) of lowest element, binary trees have logarithmic time lookup of lowest element.

提交回复
热议问题