Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparator function in Priority Queue

Tags:

c++

I'm trying to understand how the comparator function return value determines which element goes before the other when inserting into a Priority Queue.

Below code stores integers in the descending order based on a comparator function. I understand that I do not need a comparator function for this simple evaluation, but its easier to visualize with simple data.

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

struct Compfunc {
    bool operator() (const int &a, const int &b) {
        //cout << "a: " << a << " vs b: " << b << endl;
        return (a < b);
    }
};

void callPQ(vector<int> &vec) {
    priority_queue<int, vector<int>, Compfunc> pq;
    
    for (auto num : vec) {
        cout << "Pushing : " << num << endl;
        pq.push(num);
    }

    cout << "Printing:" << endl;
    while (!pq.empty()) {
        cout << pq.top() << endl;
        pq.pop();
    }
}

int main()
{
    vector<int> vec{5, 6, 4, 9, 2, 0};
    
    callPQ(vec);
    return 0;
}

Output,

Pushing : 5
Pushing : 6
Pushing : 4
Pushing : 9
Pushing : 2
Pushing : 0
Printing:
9
6
5
4
2
0

From http://www.cplusplus.com/reference/queue/priority_queue/

The expression comp(a,b), where comp is an object of this type and a and b are elements in the container, shall return true if a is considered to go before b in the strict weak ordering the function defines.

Is the following observation correct?

  1. Whenever an entry is pushed into pq, does it always become b element in compfunc?
  2. If (1) is correct, then when I push 6 in pq, a = 5 and b = 6. And the return is true i.e., 5 < 6, meaning that 5 goes before 6 in pq, but in fact 6 should become the top of pq.

I'm puzzled on (2) and how the Compfunc comparison works.

like image 325
adizone Avatar asked Nov 07 '25 11:11

adizone


1 Answers

  1. When and with what parameters the comparator is called depends on the implementation alone.

  2. https://en.cppreference.com/ is a bit more detailed and more precise than the reference you used. It states about the comparator:

    Note that the Compare parameter is defined such that it returns true if its first argument comes before its second argument in a weak ordering. But because the priority queue outputs largest elements first, the elements that "come before" are actually output last. That is, the front of the queue contains the "last" element according to the weak ordering imposed by Compare.

    I hope this answers your question(s).

like image 146
churill Avatar answered Nov 09 '25 00:11

churill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!