vik-y
5/18/2017 - 6:06 PM

MinHeap example in C++

MinHeap example in C++

#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>

// Modify the comparator function to change the heap type
struct comparator {
 bool operator()(int i, int j) {
 return i > j; 
 }
};

// The more correct way of writing a comparator would be to write a comparator clas
// and pass it as an argument

class Compare{
public:
 bool operator()(int i, int j){
  return i>j;
 }
}; 

int main(){
  int myints[] = {10,20,30,5,15};
  // priority_queue is defined inside queue library and that's why you need to include queue before using it.
  
  // Need to understand what the 2nd argument in template about
  std::priority_queue<int, std::vector<int>, comparator> minHeap;
 
  // min priority queue can also be implemented with comparator using this syntax
  // priority_queue< int, vector <int> , greater<int> > pq;

  for(int i=0;i<5;i++){
    minHeap.push(myints[i]);
  }
  std::cout << minHeap.size() << '\n';
  std::cout << minHeap.top() << '\n'; // Get the element at top of the heap
  minHeap.pop(); // Remove the top element
  std::cout << minHeap.top() << '\n';
}