stl heap

// range heap example
#include <iostream>     // std::cout
#include <algorithm>    // std::make_heap, std::pop_heap, std::push_heap, std::sort_heap
#include <vector>       // std::vector

int main () {
  int myints[] = {10,20,30,5,15};
  std::vector<int> v(myints,myints+5);

  std::make_heap (v.begin(),v.end());
  std::cout << "initial max heap   : " << v.front() << '\n';

  std::pop_heap (v.begin(),v.end()); v.pop_back();
  std::cout << "max heap after pop : " << v.front() << '\n';

  v.push_back(99); std::push_heap (v.begin(),v.end());
  std::cout << "max heap after push: " << v.front() << '\n';

  std::sort_heap (v.begin(),v.end());

  std::cout << "final sorted range :";
  for (unsigned i=0; i<v.size(); i++)
    std::cout << ' ' << v[i];

  std::cout << '\n';

  return 0;
}


Output:

initial max heap   : 30
max heap after pop : 20
max heap after push: 99
final sorted range : 5 10 15 20 99

Make: 

make_heap 将vector中元素排列成heap,root在第一个。 

30	20	10	5	15

Pop:

1)pop_heap 将vector中的最大(小)值放到最后一个。

20	15	10	5	30

2)vector.pop_back 将最后一个值删除。

20	15	10	5

Push:

1)vector.push_back 将要加入的元素放入vector的最后一位。 // insert 18

20	15	10	5	18

2)push_heap 将vector重新排列成heap。 

20	18	10	5	15
 


posted @ 2016-01-06 09:11  飞飞喵  阅读(212)  评论(1编辑  收藏  举报