Rohit N
Rohit N

Reputation: 53

Same comparison function giving different output for Sort and Priority Queue in C++

I am trying to understand how custom comparison function work in STL. I wrote below program and passed the custom function to STL sort function and priority queue. I expected both the output of both to be sorted in ascending order but that's not the case.

#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;

struct compareStruct {
  bool operator() (int i,int j) 
  { 
    return (i<j);
  }
} compare;


int main() {

    int numbers[] = {32,71,12,45,26,80,53,33};
    vector<int> myvector (numbers, numbers+8);  
    sort (myvector.begin(), myvector.end(), compare);

    priority_queue<int, vector<int>, compareStruct> mypq;
    for(int i=0;i<8;i++)
    {
        mypq.push(numbers[i]);
    }

    cout<<"Vector Sort Output :\n";
    for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
        cout << *it<<" ";

    cout<<"\nPriority Queue Output: \n";
    while(!mypq.empty())
    {
        cout << mypq.top()<<" ";
        mypq.pop();
    }
    return 0;
}

The output of above program is:

Vector Sort Output : 12 26 32 33 45 53 71 80 Priority Queue Output: 80 71 53 45 33 32 26 12

Upvotes: 2

Views: 648

Answers (1)

Matthieu Brucher
Matthieu Brucher

Reputation: 22023

The priority queue sorts in the opposite order, the first being the largest, and not the smallest (see the reference).

If you want the same order, use:

priority_queue<int, vector<int>, greater<int>> mypq;

Upvotes: 5

Related Questions