我对 C++ 很陌生,我想知道是否有办法从标准库中用 C++ 创建一个最小堆。
问问题
41617 次
2 回答
47
使用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;
}
于 2010-05-07T08:13:25.473 回答
4
您可以直接使用std::make_heap
、std::push_heap
和其他,也可以使用std::priority_queue
基于 astd::vector
或类似的构建。
std::*_heap
方法在 中,<algorithm>
模板std::priority_queue
在 中<queue>
。
于 2010-05-07T05:32:29.230 回答