c++ - STL priority_queue 的效率

标签 c++ data-structures stl performance priority-queue

我有一个应用程序 (C++),我认为 STL priority_queue 可以很好地提供服务。 The documentation说:

Priority_queue is a container adaptor, meaning that it is implemented on top of some underlying container type. By default that underlying type is vector, but a different type may be selected explicitly.

Priority queues are a standard concept, and can be implemented in many different ways; this implementation uses heaps.

我之前假设 top()O(1),而push()将是 O(logn) (我首先选择 priority_queue 的两个原因) - 但文档既不确认也不否认这一假设。

深入挖掘,序列概念的文档说:

The complexities of single-element insert and erase are sequence dependent.

priority_queue 使用 vector(默认)作为堆,其中:

... supports random access to elements, constant time insertion and removal of elements at the end, and linear time insertion and removal of elements at the beginning or in the middle.

我推断,使用默认的 priority_queuetop()O(1)push() O(n)

问题 1:这是正确的吗? (top() 访问是 O(1) 并且 push()O(n)?)

问题 2: 如果我使用 set,我能否在 push() 上实现 O(logn) 效率(或multiset)而不是vector 来实现priority_queue?这样做会有什么后果?其他操作会因此受到影响?

注:我担心的是时间效率,而不是空间。

最佳答案

优先级队列适配器使用标准库堆算法来构建和访问队列 - 您应该在文档中查找这些算法的复杂性。

top() 操作显然是 O(1) 但大概你想在调用它之后 pop() 堆(根据 Josuttis )是 O(2*log(N)) 并且 push() 是O(log(N)) - 相同的来源。

并且来自 C++ 标准,25.6.3.1,push_heap:

Complexity: At most log(last - first) comparisons.

和pop_heap:

Complexity: At most 2 * log(last - first) comparisons.

关于c++ - STL priority_queue 的效率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2974470/

相关文章:

c++ - 初始化时将函数作为构造函数参数传递给基类构造函数

algorithm - 是否存在用于存储关系的概率数据结构?

python - 连接具有相同 id Pandas DataFrame 的列

c++ - 指向动态容器的指针是否持续存在?

c++ - 如何使用 STL 从容器集中删除自定义对象?

c++ - 为什么对 BeginPaint() 的调用总是生成 WM_NCPAINT 消息?

c++ - 从 map 容器中查找第一个大于用户指定值的值

c++ - 尝试在单击按钮时从编辑框中捕获文本,然后显示到另一个编辑框

mysql - 你会如何设计这个数据库?

c++ - 如何像 c 数组一样初始化 'const std::vector<T>'