CPP STL Tutorial : C++ Heap operation that can be performed on containers

To use these heap operations, below header should be included:
#include <algorithm>
push_heap : It will push element into heap range
pop_heap : It will pop element from heap range
make_heap : It will make heap from range
sort_heap : It will sort elements of heap
is_heap   : It will test if range is heap
is_heap_until   : It will find first element not in heap order

Example:

#include <iostream>
#include <vector>
#include <array>
#include <algorithm>    // std::all_of

//for more tutorials on C, C++, STL, DS visit www.ProDeveloperTutorial.com
using namespace std;

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

  if(std::is_heap(v.begin(),v.end()))
  {
        cout<<"v is heap before make_heap"<<endl;
  }
  else
  {
        cout<<"v is not heap before make_heap"<<endl;
  }
  
  std::make_heap (v.begin(),v.end());

  if(std::is_heap(v.begin(),v.end()))
  {
      cout<<"v is heap after make_heap"<<endl;
  }
  else
  {
    cout<<"v is not heap after make_heap"<<endl;
  }
  
  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:
v is not heap before make_heap
v is heap after make_heap
initial max heap : 30
max heap after pop : 25
max heap after push: 99
final sorted range : 5 10 15 20 25 99
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *