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/

隐藏行号 复制代码 Demo
  1. #include<iostream>
    
  2. #include<algorithm>
    
  3. #include<vector>
    
  4. using namespace std;
    
  5. void print_ivec(vector<int>::iterator begin, vector<int>::iterator end)
    
  6. {
    
  7.     for(;begin != end; ++begin)
    
  8.         cout << *begin << '\t';
    
  9.     cout << endl;
    
  10. }
    
  11. int main(int argc, char* argv[])
    
  12. {
    
  13.     int a[] = {1, 12, 15, 20, 30};
    
  14.     vector<int> ivec(a, a + sizeof(a) / sizeof(a[0]));
    
  15.     print_ivec(ivec.begin(), ivec.end());
    
  16.     make_heap(ivec.begin(), ivec.end(), greater<int>());
    
  17.     print_ivec(ivec.begin(), ivec.end());
    
  18.     pop_heap(ivec.begin(), ivec.end());
    
  19.     ivec.pop_back();
    
  20.     print_ivec(ivec.begin(), ivec.end());
    
  21.     ivec.push_back(99);
    
  22.     push_heap(ivec.begin(), ivec.end());
    
  23.     print_ivec(ivec.begin(), ivec.end());
    
  24.     sort_heap(ivec.begin(), ivec.end());
    
  25.     print_ivec(ivec.begin(), ivec.end());
    
  26.     return 0;
    
  27. }
    
  28. 
    

Container Adaptors(容器适配器)priority_queue提供了更方便的堆数据结构,操作像queue, stack 一样简单方便,详情参见:

http://www.cplusplus.com/reference/stl/priority_queue/

 

隐藏行号 复制代码 Demo
  1. #include<iostream>
    
  2. #include<algorithm>
    
  3. #include<queue>
    
  4. using namespace std;
    
  5. int main(int argc, char* argv[])
    
  6. {
    
  7.     priority_queue<int, vector<int>, greater<int>() > pq;
    
  8.     pq.push(676);
    
  9.     pq.push(34);
    
  10.     pq.push(23);
    
  11.     while(!pq.empty())
    
  12.     {
    
  13.         cout << pq.top() << endl;
    
  14.         pq.pop();
    
  15.     }
    
  16.     return 0;
    
  17. }
    
  18. 
    

posted @ 2009-12-13 20:24  dskit  阅读(6710)  评论(2编辑  收藏  举报