Last active
June 19, 2017 13:17
-
-
Save vik-y/ac9711e23c3a37e10bc02e9ee16fbcf7 to your computer and use it in GitHub Desktop.
MinHeap example in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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