C++ STL 堆

#include <queue>
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    //大根堆
    //push,pop,top,empty,size
    priority_queue<int> a;
    a.push(3);
    a.push(1);
    a.push(20);
    a.push(15);
    cout << a.top() << endl;
    //小根堆
    priority_queue<int, vector<int>, greater<int>> b;
    b.push(3);
    b.push(1);
    b.push(20);
    b.push(15);
    cout << b.top() << endl;
    //使用几个根堆相关的函数
    //make_heap: 根据指定的迭代器区间以及一个可选的比较函数,来创建一个heap. O(N)
    //push_heap: 把指定区间的最后一个元素插入到heap中. O(logN)
    //pop_heap: 弹出heap顶元素, 将其放置于区间末尾. O(logN)
    //sort_heap:堆排序算法,通常通过反复调用pop_heap来实现. N*O(logN)
    vector<int> c = {3, 1, 20, 15, 6, 8, 9, 2};
    make_heap(c.begin(), c.end());
    for(auto cc:c)
        cout << cc << " ";
    cout << endl;
    pop_heap(c.begin(), c.end());
    for(auto cc:c)
        cout << cc << " ";
    cout << endl;
    return 0;
}
发布了27 篇原创文章 · 获赞 70 · 访问量 9411

猜你喜欢

转载自blog.csdn.net/qq_23905237/article/details/90905635