有一个简单的方法来做一个最小的堆在C + +? [英] Is there an easy way to make a min heap in C++?

查看:355
本文介绍了有一个简单的方法来做一个最小的堆在C + +?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++的新手,我想知道是否有一种方法可以从标准库中创建C ++的最小堆。

I'm very new to C++, and I was wondering if there was a way to make a min heap in C++ from the standard library.

推荐答案

使用< algorithm> 中定义的 make_heap() code>< queue> 中定义的code> priority_queue 。 priority_queue 使用 make_heap 和下面的朋友。

Use make_heap() and friends, defined in <algorithm>, or use priority_queue, defined in <queue>. The priority_queue uses make_heap and friends underneath.

#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 + +?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆