Is there an easy way to make a min heap in C++?

ε祈祈猫儿з 提交于 2019-12-17 22:40:07

问题


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.


回答1:


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;
}



回答2:


You can use std::make_heap, std::push_heap, and others directly, or you can use a std::priority_queue built on a std::vector or similar.

The std::*_heap methods are in <algorithm>, and the std::priority_queue template is in <queue>.



来源:https://stackoverflow.com/questions/2786398/is-there-an-easy-way-to-make-a-min-heap-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!