Create a heap, adds and removes elements, sort the heap. - C++ STL Algorithm

C++ examples for STL Algorithm:pop_heap

Description

Create a heap, adds and removes elements, sort the heap.

Demo Code

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void show(const char *msg, vector<char> vect);
int main()//from   w  w w .  j a  v a  2  s .c om
{
   vector<char> v;
   int i;
   for(i=0; i<20; i+=2) 
      v.push_back('A'+i);
   show("v before building heap:\n", v);
   cout << endl;
   // Construct a heap.
   make_heap(v.begin(), v.end());
   show("v after building heap:\n", v);
   cout << endl;
   // Push H onto heap.
   v.push_back('H'); // first put H into vector
   push_heap(v.begin(), v.end()); // now, push H onto heap
   show("v after pushing H onto heap:\n", v);
   cout << endl;
   // Pop value from heap.
   pop_heap(v.begin(), v.end());
   show("v after popping from heap:\n", v);
   cout << endl;
   // Sort the heap
   sort_heap(v.begin(), v.end()-1);
   show("v after sorting the heap:\n", v);
   return 0;
}
// Display the contents of a vector<char>.
void show(const char *msg, vector<char> vect) {
   cout << msg;
   for(unsigned i=0; i < vect.size(); ++i)
      cout << vect[i] << " ";
   cout << "\n";
}

Result


Related Tutorials