我对 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/