gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:00:22 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com