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

后端 未结 2 421
长发绾君心
长发绾君心 2020-12-14 02:43

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.

2条回答
  •  心在旅途
    2020-12-14 03:15

    Use make_heap() and friends, defined in , or use priority_queue, defined in . The priority_queue uses make_heap and friends underneath.

    #include  // functional,iostream,ctime,cstdlib
    using namespace std;
    
    int main(int argc, char* argv[])
    {
        srand(time(0));
        priority_queue,greater > 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;
    }
    

提交回复
热议问题