1. 头文件
堆的使用在头文件<algorithm>中定义
2. 创建堆:make_heap()
默认创建大顶堆,如果想要创建小顶堆,则需要在函数添加第三个参数:greater<int>。
#include<iostream>
#include<algorithm>
using namespace std;
int main () {
vector<int> heap = { 1,2,3,4,5,6,7,8,9,10 };
cout << "原数组:";
for (int x : heap) {
cout << x << " ";
}
cout << endl;
make_heap (heap.begin () , heap.end ());
cout << "建堆后:";
for (int x : heap) {
cout << x << " ";
}
cout << endl;
system ("pause");
return 0;
}
3. 判断数组是否是堆 is_heap()
#include<iostream>
#include<algorithm>
using namespace std;
int main () {
vector<int> heap = { 1,2,3,4,5,6,7,8,9,10 };
make_heap (heap.begin () , heap.end ());
cout << "原堆:";
for (int x : heap) {
cout << x << " ";
}
cout << endl;
cout << (is_heap (heap.begin () , heap.end ()) ? "Yes" : "No") << endl;
//当我们再 push 一个数到数组中,将不再是一个堆
heap.push_back (11);
cout << (is_heap (heap.begin () , heap.end ()) ? "Yes" : "No") << endl;
system ("pause");
return 0;
}
4. 添加与删除 push_heap() & pop_heap()
4.1 push_heap()
因为make_heap只能建堆,如果当前堆数据发生改变,就需要使用push_heap重回大堆/小堆。
ps:first 到 last - 1 之间的元素必须满足堆结构。它仅仅是将数组中的最后一个元素加入到堆中。
#include<iostream>
#include<algorithm>
using namespace std;
int main () {
vector<int> heap = { 1,2,3,4,5,6,7,8,9,10 };
make_heap (heap.begin () , heap.end ());
cout << "原堆:";
for (int x : heap) {
cout << x << " ";
}
cout << endl;
heap.push_back (11);
push_heap (heap.begin () , heap.end ());
cout << "插入元素到堆中:";
for (int x : heap) {
cout << x << " ";
}
cout << endl;
system ("pause");
return 0;
}
4.2 pop_heap()
类似于 push_heap ,pop_heap 也仅仅是将堆顶元素放入到数组的尾部
#include<iostream>
#include<algorithm>
using namespace std;
int main () {
vector<int> heap = { 1,2,3,4,5,6,7,8,9,10 };
make_heap (heap.begin () , heap.end ());
cout << "原堆:";
for (int x : heap) {
cout << x << " ";
}
cout << endl;
pop_heap (heap.begin () , heap.end ());
cout << "删除堆顶元素后:";
for (int x : heap) {
cout << x << " ";
}
cout << endl;
system ("pause");
return 0;
}
5. 堆排序sort_heap()
默认按升序将堆排序,如果想要按降序排序,则需要在函数添加第三个参数:greater<int>。
#include<iostream>
#include<algorithm>
using namespace std;
int main () {
vector<int> heap = { 1,2,3,4,5,6,7,8,9,10 };
make_heap (heap.begin () , heap.end ());
cout << "原堆:";
for (int x : heap) {
cout << x << " ";
}
cout << endl;
sort_heap (heap.begin () , heap.end ());
cout << "排序后:";
for (int x : heap) {
cout << x << " ";
}
cout << endl;
system ("pause");
return 0;
}
6. 另外的使用方法
在 C++ 的另一个头文件<queue>中,有一个叫做 priority_queue 的容器,如果熟悉堆(或者说优先队列)的话,你或许已经知道如何使用了。