stl里关于heap的函数与priority_queue的区别

大家都知道,priority_queue是用堆实现的,可以通过重载()运算符选择使用最大堆或最小堆。以前一直觉得stl里面的heap相关的函数都是多余的,因为一般的heap操作都可以用priority_queue来做。直到今天看了July博客中的那道求前k小的数(http://blog.csdn.net/v_JULY_v/article/details/6370650)才发现stl中heap操作独立存在的必要。


在求前k小的数这道题中,有一个解法是,用最小堆初始化数组,然后取前k小的数,复杂度是建堆O(N)+取数O(K*log(N))。原来,对一个数组进行建堆的复杂度是O(N),可以用stl中的make_heap来建堆,而如果用priority_queue没有办法在O(N)复杂度建堆。

下面是个使用stl中heap相关函数的例子,注意头文件是

// range heap example
#include      // std::cout
#include     // std::make_heap, std::pop_heap, std::push_heap, std::sort_heap
#include        // std::vector

int main () {
  int myints[] = {10,20,30,5,15};
  std::vector 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




你可能感兴趣的:(STL/C++,算法分析,面试准备)