We have a question, which discusses how to use a comparator in priority_queue
in C++. He gives the overloaded operator
class
(or struct
) as the third argument and it works fine. But bool
function doesn't work. Why ? But it works fine in sort
of the <algorithm>
. When I looked into docs (priority_queue && algo/sort), both of them take the class Compare
as their optional third argument.
#include <iostream>
#include <cstdio>
#include <queue>
#include <algorithm>
#include <vector>
using namespace std;
bool cmp (const int &a,const int &b){ return a > b; }
struct cmp2
{
bool operator() (const int &p1,const int &p2)
{
return p1 > p2;
}
};
int main ()
{
// freopen("test.txt","r",stdin);
int a[10];
vector<int> b(10);
sort( a , a + 10, cmp ); // working cool
sort( b.begin() , b.end() , cmp); // working great
priority_queue<int, vector<int> , cmp2 > x; // as usual, working....
priority_queue<int, vector<int> , cmp > y; // not working why ?
return 0;
}
Errors:
A:\pqvsarray.cpp In function 'int main()':
27 40 A:\pqvsarray.cpp [Error] type/value mismatch at argument 3 in template parameter list for 'template<class _Tp, class _Sequence, class _Compare> class std::priority_queue'
27 40 A:\pqvsarray.cpp [Error] expected a type, got 'cmp'
27 43 A:\pqvsarray.cpp [Error] invalid type in declaration before ';' token
So, why the difference ?