C++用vector容器实现堆的相关算法
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
vector<int> v = {0, 1, 2, 3, 4, 5, 6};
make_heap(v.begin(), v.end());
for (auto i : v) {
cout << i << " ";
}
cout << endl;
v.push_back(7);
push_heap(v.begin(), v.end());
for (auto i : v) {
cout << i << " ";
}
cout << endl;
pop_heap(v.begin(), v.end());
cout << v.back() << endl;
v.pop_back();
for (auto i : v)
{
cout << i << " ";
}
cout << endl;
sort_heap(v.begin(), v.end());
for (auto i : v)
{
cout << i << " ";
}
return 0;
}
运行结果