当前位置: 代码迷 >> 综合 >> STL 堆
  详细解决方案

STL 堆

热度:98   发布时间:2024-02-09 01:47:16.0

1.priority_queue

priority_queue默认是最大堆,要用最小堆需要比较函数greater<int>

priority_queue<int, vector<int>, less<int>> maxHeap;
priority_queue<int, vector<int>, greater<int>> minHeap;

也可以自定义比较函数

struct cmp
{bool operator()(const int &a, const int &b)//operator()重载函数需要被定义(声明)在一个新的结构体内{return a > b;}
};
priority_queue<int, vector<int>, cmp> minHeap;

如果不是内置类型,也可以

struct cmp
{bool operator()(const Node&a, const Node&b)//operator()重载函数需要被定义(声明)在一个新的结构体内{return a.val > b.val;}
};

比较函数若使用operator<(使用该方法的前提是有默认的比较函数会调用我们的 operator<),可放在自定义类型的声明的外面或里面

struct Node //运算符重载<
{int val;Node (int a) {val = a;}//放在自定义类型的声明里面bool operator<(const Node& a) const{return val < a.val; //大顶堆}
};//放在自定义类型的声明外面
bool operator<(Node a, Node b)
{return a.val> b.val;
}priority_queue<Node> pq;

2. STL 堆操作

头文件是#include <algorithm>
一般用到这四个:make_heap()、pop_heap()、push_heap()、sort_heap();
(1)make_heap()构造堆
void make_heap(first_pointer,end_pointer,compare_function);
默认比较函数是(<),即最大堆。
函数的作用是将[begin,end)内的元素处理成堆的结构

(2)push_heap()添加元素到堆
void push_heap(first_pointer,end_pointer,compare_function);
新添加一个元素在末尾,然后重新调整堆序。该算法必须是在一个已经满足堆序的条件下。
先在vector的末尾添加元素,再调用push_heap

(3)pop_heap()从堆中移出元素
void pop_heap(first_pointer,end_pointer,compare_function);
把堆顶元素取出来,放到了数组或者是vector的末尾。
要取走,则可以使用底部容器(vector)提供的pop_back()函数。
先调用pop_heap再从vector中pop_back元素

(4)sort_heap()对整个堆排序
排序之后的元素就不再是一个合法的堆了。

用法:

void testHeap() {vector<int> data{ 3,1,2,7,5 };//构造堆,最大堆make_heap(data.begin(), data.end(), less<int>());//pop堆顶元素,最大的元素pop_heap(data.begin(), data.end(), less<int>());cout << data.back() << endl;//输出7data.pop_back();//往堆中添加元素data.push_back(4);push_heap(data.begin(), data.end(), less<int>());//调整堆//排序sort_heap(data.begin(), data.end(), less<int>());for (int x : data)cout << x << " ";cout << endl;//输出 1,2,3,4,5
}
  相关解决方案