20

私は C++ に非常に慣れていないので、標準ライブラリから C++ で最小ヒープを作成する方法があるかどうか疑問に思っていました。

4

2 に答える 2

47

で定義されたusemake_heap()とフレンド、<algorithm>またはpriority_queueで定義されたuse <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_heapstd::push_heap、およびその他を直接使用することも、または同様のものに組み込まれた を使用することもできますstd::priority_queuestd::vector

std::*_heapメソッドは にあり<algorithm>std::priority_queueテンプレートは にあり<queue>ます。

于 2010-05-07T05:32:29.230 に答える