c++ - 有没有一种简单的方法可以在 C++ 中创建最小堆?

标签 c++ data-structures heap min

我对 C++ 很陌生,我想知道是否有办法从标准库中创建 C++ 中的最小堆。

最佳答案

使用 make_heap()和 friend ,定义在 <algorithm> , 或使用 priority_queue , 在 <queue> 中定义. priority_queue使用 make_heap和下面的 friend 。

#include <queue> // functional,iostream,ctime,cstdlib
using namespace std;

int main(int argc, char* argv[])
{
    srand(time(0));
    priority_queue<int,vector<int>,greater<int> > q;
    for( int i = 0; i != 10; ++i ) q.push(rand()%10);
    cout << "Min-heap, popped one by one: ";
    while( ! q.empty() ) {
        cout << q.top() << ' ';  // 0 3 3 3 4 5 5 6 8 9
        q.pop();
    }
    cout << endl;
    return 0;
}

关于c++ - 有没有一种简单的方法可以在 C++ 中创建最小堆?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2786398/

相关文章:

java - 如何修复堆结构的循环

Python:heapq.heappop() 给出奇怪的结果

c++ - std::map 以 std::string* 作为键

c++ - 如何将智能指针与 Allegro 位图一起使用?

c++ - 在 C++ 项目中使用基于 CUDA 的库代码

c++ - 类型 'long long int' 到二进制 'operator%' 的无效操作数

string - 畸形二叉绳树

python - 如何使用 defaultdict 行为扩展 OrderedDict

.net - 结构 "faster"比类 - 通常还是在 .NET 框架中?

performance - 合并两个堆 : O(n*log(n)) vs. O(n + m)