C++中堆(优先队列)的应用:make_heap, pop_heap, push_heap, sort_heap, priority_queue
C++中堆的应用:make_heap, pop_heap, push_heap, sort_heap, priority_queue
make_heap, pop_heap, push_heap, sort_heap都是标准算法库里的模板函数,用于将存储在vector/deque 中的元素进行堆操作,对不愿自己写数据结构堆的C++选手来说,这几个算法函数很有用,下面是这几个函数操作vector中元素的例子。详细解释可以参见: http://www.cplusplus.com/reference/algorithm/push_heap/
-
#include<iostream>
-
#include<algorithm>
-
#include<vector>
-
using namespace std;
-
void print_ivec(vector<int>::iterator begin, vector<int>::iterator end)
-
{
-
for(;begin != end; ++begin)
-
cout << *begin << '\t';
-
cout << endl;
-
}
-
int main(int argc, char* argv[])
-
{
-
int a[] = {1, 12, 15, 20, 30};
-
vector<int> ivec(a, a + sizeof(a) / sizeof(a[0]));
-
print_ivec(ivec.begin(), ivec.end());
-
make_heap(ivec.begin(), ivec.end(), greater<int>());
-
print_ivec(ivec.begin(), ivec.end());
-
pop_heap(ivec.begin(), ivec.end());
-
ivec.pop_back();
-
print_ivec(ivec.begin(), ivec.end());
-
ivec.push_back(99);
-
push_heap(ivec.begin(), ivec.end());
-
print_ivec(ivec.begin(), ivec.end());
-
sort_heap(ivec.begin(), ivec.end());
-
print_ivec(ivec.begin(), ivec.end());
-
return 0;
-
}
Container Adaptors(容器适配器)priority_queue提供了更方便的堆数据结构,操作像queue, stack 一样简单方便,详情参见:
http://www.cplusplus.com/reference/stl/priority_queue/
-
#include<iostream>
-
#include<algorithm>
-
#include<queue>
-
using namespace std;
-
int main(int argc, char* argv[])
-
{
-
priority_queue<int, vector<int>, greater<int>() > pq;
-
pq.push(676);
-
pq.push(34);
-
pq.push(23);
-
while(!pq.empty())
-
{
-
cout << pq.top() << endl;
-
pq.pop();
-
}
-
return 0;
-
}