Skip to content

Instantly share code, notes, and snippets.

@vik-y
Last active June 19, 2017 13:17
Show Gist options
  • Save vik-y/ac9711e23c3a37e10bc02e9ee16fbcf7 to your computer and use it in GitHub Desktop.
Save vik-y/ac9711e23c3a37e10bc02e9ee16fbcf7 to your computer and use it in GitHub Desktop.
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';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment