how to use priority queue constructor c++ code example

Example 1: how to use priority queue comparator stl c++

void SamplePriorityQueueWithLamda()
{
    // using lambda to compare elements.
    auto compare = [](int lhs, int rhs)
                {
                    return lhs < rhs;
                };

    std::priority_queue<int, std::vector<int>, decltype(compare)> q(compare);

    for(int n : {1,8,5,6,3,4,0,9,7,2})
        q.push(n);


    printQueue(q);
}

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>
#define pp pair<int, int>
priority_queue <pp, vector<pp>, greater<pp> > pq;

Tags:

Cpp Example