I tried making the same comparator for vector and priority queue, but they give reverse results. Why is it so?
Code:
struct cmp {
bool operator()(int a, int b)
{
return a<b;
}
};
bool compare(int a, int b)
{
return a<b;
}
int main()
{
priority_queue<int,vector<int>, cmp> numbers;
vector<int>v;
v.push_back(1);
v.push_back(20);
v.push_back(7);
sort(v.begin(), v.end(), compare);
numbers.push(1);
numbers.push(20);
numbers.push(7);
cout << "Priority Queue: ";
while(!numbers.empty()) {
cout << numbers.top() << ", ";
numbers.pop();
}
cout << endl;
cout<<"Vector: ";
int i=0;
while(i<v.size()) {
cout << v[i] << ", ";
i++;
}
cout << endl;
return 0;
}
//Output:
Priority Queue: 20, 7, 1,
Vector: 1, 7, 20,
//Output: Priority Queue: 20, 7, 1, Vector: 1, 7, 20,
Please clarify the confusion. Thanks
Yes, they work in reverse. For one possible reference, see cppreference's description of std::priority_queue:
Template parameters
[...]
Compare- A Compare type providing a strict weak ordering.Note that the Compare parameter is defined such that it returns
trueif 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With