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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2786398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:39:57  来源:igfitidea点击:

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

c++data-structuresheapmin

提问by Alex

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.

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

回答by wilhelmtell

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

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

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

回答by jemfinch

You can use std::make_heap, std::push_heap, and others directly, or you can use a std::priority_queuebuilt on a std::vectoror similar.

您可以直接使用std::make_heapstd::push_heap和 其他,也可以使用std::priority_queue构建于std::vector或类似的。

The std::*_heapmethods are in <algorithm>, and the std::priority_queuetemplate is in <queue>.

std::*_heap方法是<algorithm>,和std::priority_queue模板中<queue>