make_heap |
把数组或vector化为heap
make_heap(ans, ans+sizeof(ans)/sizeof(ans[0]), cmp=less<>())[数组]或
make_heap(ans.begin(), ans.end(), cmp=less<>())[vector]
默认是最大堆,也可以自己定义cmp改变规则
|
push_heap |
只能对vector进行操作,因为在进行此操作前,首先得在尾端添加元素
vec.push_back(val);
push_heap(vec.begin(), vec.end(), cmp=less<>());
|
pop_heap |
把堆顶元素置为堆尾
vec.pop_heap(vec.begin(), vec.end(), cmp=less<>());
默认最大堆
|
sort_heap |
1,如果堆是最大堆,则应非减排序;如果堆是最小堆,则应非增排序;否则就会排序出错,出现堆是无效堆
2,sort_heap(vec.begin(),vec.end(), cmp=greater<>())
|
以下是实践代码:
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <iterator>
#include <ctime>
#include <functional>
using namespace std;
const int MAX_N = 5;
void O(vector<int>vec, char* s)
{
cout << s << endl;
copy(vec.begin(), vec.end(), ostream_iterator<int>(cout, " "));
cout << endl << endl;
}
int main()
{
vector<int>vec;
int i, j, k;
srand(time(NULL));
for (i = 0; i < MAX_N; i++)
vec.push_back(rand()%1000);
O(vec, "----init vector----");
make_heap(vec.begin(), vec.end(), greater<int>());
O(vec, "----after make_heap----");
sort_heap(vec.begin(), vec.end(), greater<int>());
O(vec, "----after sort_heap----");
i = rand()%1000;
cout << "the value of push_back = " << i << endl;
vec.push_back(i);
push_heap(vec.begin(), vec.end(), greater<int>());
O(vec, "----after push_heap----");
pop_heap(vec.begin(), vec.end());
O(vec, "----after pop_head----");
pop_heap(vec.begin(), vec.end());
O(vec, "----after pop_head----");
exit(0);
}