Example 1: comparator for priority queue c++
class Foo
{
};
class Compare
{
public:
bool operator() (Foo, Foo)
{
return true;
}
};
int main()
{
std::priority_queue<Foo, std::vector<Foo>, Compare> pq;
return 0;
}
Example 2: implemetation of priority queue in c++
// Implementation of priority_queue in c++
//queue with elements in decreasing order
priority_queue<int> pq;
// queue with elements in increasing order using compare function inside declaration
priority_queue <int, vector<int>, greater<int> > pq;
//priority_queue of type pair<int, int>
priority_queue <pp, vector<pp>, greater<pp> > pq;
Example 3: priority queue cpp
// using GCC 10.2 (C++2a) compiler
template<typename T> void print_queue(T& q) {
while(!q.empty()) {
std::cout << q.top() << " ";
q.pop();
}
std::cout << '\n';
}
int main() {
std::priority_queue<int> q;
for(int n : {1,8,5,6,3,4,0,9,7,2})
q.push(n);
print_queue(q);
std::priority_queue<int, std::vector<int>, std::greater<int> > q2;
for(int n : {1,8,5,6,3,4,0,9,7,2})
q2.push(n);
print_queue(q2);
// Using lambda to compare elements.
auto cmp = [](int left, int right) { return (left ^ 1) < (right ^ 1); };
std::priority_queue<int, std::vector<int>, decltype(cmp)> q3(cmp);
for(int n : {1,8,5,6,3,4,0,9,7,2})
q3.push(n);
print_queue(q3);
}
Example 4: priority queue in c++
//Shubh'grepper
// Implementation of priority_queue in c++
//queue with elements in decreasing order
priority_queue<int> pq;
// queue with elements in increasing order using compare function inside declaration
priority_queue <int, vector<int>, greater<int> > pq;
//priority_queue of type pair<int, int>
priority_queue <pp, vector<pp>, greater<pp> > pq;