1、make_heap(): 将已有的数据排序,按照堆存储的要求
2、sort_heap(): 堆排序,对一个堆结构进行排序。注意,如果没有待排序的数据不是按照堆的形式排序,则会排序失败。
3、pop_heap():在已有的堆结构中,删除堆顶元素
4、push_heap():将新元素插入到堆中
5、is_heap() :判断一个数据队列是否为堆
6、is_heap_until(): 判断一个数据队列是否为堆,同时返回第一个不满足堆结构的数据的迭代器
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void Display(vector<int>& nums) {
for (auto& iter : nums)
cout << iter << " ";
cout << endl;
}
int main()
{
vector<int> v{
12,3,1,3,4,5,6,75,23,-9,3,43 };
// 判断序列是否为一个堆,即是否按照堆的结构进行存储
if (!is_heap(v.begin(), v.end())) {
cout << "is_heap : v is not heap!!!" << endl;
}
// 返回序列中第一个不满足堆数据结构的元素
auto iter = is_heap_until(v.begin(), v.end());
cout << "is_heap_until :" << *iter << endl;
// 将序列重新排列,转化为堆
cout << "max value after make_heap : ";
make_heap(v.begin(), v.end());
cout << v.front() << endl;
// 删除堆顶元素:即将堆顶元素放到数组的末尾
cout << "max value after pop_heap : ";
pop_heap(v.begin(), v.end()); v.pop_back();
cout << v.front() << endl;
// 插入一个新元素到堆中:插入一个元素到数组中,重新进行堆的构造
cout << "max value after push_heap : ";
v.emplace_back(166); push_heap(v.begin(), v.end());
cout << v.front() << endl;
// 未排序前的堆结构
cout << "heap not sort : ";
Display(v);
// 对一个堆结构进行堆排序
cout << "after sort_heap : ";
sort_heap(v.begin(), v.end());
Display(v);
return 0;
}
输出结果:
is_heap : v is not heap!!!
is_heap_until :4
max value after make_heap : 75
max value after pop_heap : 43
max value after push_heap : 166
heap not sort : 166 23 43 12 4 6 1 3 3 -9 3 5
after sort_heap : -9 1 3 3 3 4 5 6 12 23 43 166
谢谢阅读