stl中的heap使用

stl中的堆默认是最大堆,要想用最小堆的话,必须要在push_heap,pop_heap,make_heap等每一个函数后面加第三个参数greater(),括号不能省略。


1、make_heap:使序列变成堆

原型:
template
  void make_heap ( RandomAccessIterator first, RandomAccessIterator last );

template
  void make_heap ( RandomAccessIterator first, RandomAccessIterator last,
                   Compare comp );

范例:

// range heap example
#include 
#include 
#include 
using namespace std;

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

  make_heap (v.begin(),v.end());
  cout << "initial max heap   : " << v.front() << endl;

  pop_heap (v.begin(),v.end()); v.pop_back();
  cout << "max heap after pop : " << v.front() << endl;

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

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

  cout << "final sorted range :";
  for (unsigned i=0; i
2、push_heap:压栈(入栈)
原型:
template
  void push_heap ( RandomAccessIterator first, RandomAccessIterator last );

template
  void push_heap ( RandomAccessIterator first, RandomAccessIterator last,
                   Compare comp );


3、pop_heap弹栈(出栈)

原型:
template
  void pop_heap ( RandomAccessIterator first, RandomAccessIterator last );

template
  void pop_heap ( RandomAccessIterator first, RandomAccessIterator last,
                   Compare comp );

范例:

// range heap example
#include 
#include 
#include 
using namespace std;

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

  make_heap (v.begin(),v.end());
  cout << "initial max heap   : " << v.front() << endl;

  pop_heap (v.begin(),v.end()); v.pop_back();
  cout << "max heap after pop : " << v.front() << endl;

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

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

  cout << "final sorted range :";
  for (unsigned i=0; i

4、 sort_heap 对堆排序 原型:template
  void sort_heap ( RandomAccessIterator first, RandomAccessIterator last );

template
  void sort_heap ( RandomAccessIterator first, RandomAccessIterator last,
                   Compare comp );

范例:

// range heap example
#include 
#include 
#include 
using namespace std;

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

  make_heap (v.begin(),v.end());
  cout << "initial max heap   : " << v.front() << endl;

  pop_heap (v.begin(),v.end()); v.pop_back();
  cout << "max heap after pop : " << v.front() << endl;

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

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

  cout << "final sorted range :";
  for (unsigned i=0; i

注:例子来源于 www.cplusplus.com 网站

你可能感兴趣的:(C++)