Last active
March 6, 2017 12:02
-
-
Save huklee/1592d0c7179a0c17a89de5ca980e8954 to your computer and use it in GitHub Desktop.
[C++ STL] priority_queue example
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 <queue> | |
using namespace std; | |
class Node{ | |
public: | |
int val; | |
Node* left; | |
Node* right; | |
Node (int v, Node *l, Node *r) : val(v), left(l), right(r) {;} | |
}; | |
struct compare{ | |
bool operator()(const Node* l, const Node* r){ | |
return l->val < r->val; | |
} | |
}; | |
int main() | |
{ | |
// 01. Simple integer max priroity queue example | |
int ints[] = {1,5,2,3,63,63,4,24,12,4123,42}; | |
vector<int> vi(ints, ints + sizeof(ints)/sizeof(int)); | |
priority_queue<int> intMaxPQ; | |
for (int i : vi) | |
intMaxPQ.push(i); | |
while (!intMaxPQ.empty()){ | |
cout << intMaxPQ.top() << " "; | |
intMaxPQ.pop(); | |
} | |
cout << endl; | |
// 4123 63 63 42 24 12 5 4 3 2 1 | |
// 02. Simple integer min priroity queue example | |
priority_queue<int, vector<int>, std::greater<int> > intMinPQ; | |
for (int i : vi) | |
intMinPQ.push(i); | |
while (!intMinPQ.empty()){ | |
cout << intMinPQ.top() << " "; | |
intMinPQ.pop(); | |
} | |
cout << endl; | |
// 1 2 3 4 5 12 24 42 63 63 4123 | |
// 03. customized priority queue example | |
priority_queue<int, vector<Node*>, compare> nodePQ; | |
for (int i : vi){ | |
Node* n = new Node(i, nullptr, nullptr); | |
nodePQ.push(n); | |
} | |
while (!nodePQ.empty()){ | |
cout << nodePQ.top()->val << " "; | |
nodePQ.pop(); | |
} | |
cout << endl; | |
// 4123 63 63 42 24 12 5 4 3 2 1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment