I am trying to understand the priority queue in stl. What I have understood is that the third argument is basically typename(in this case function pointer). So,if it just accepts the typename, how will it have access over my compare function when it will implement its operations if it just accept typename and not actual function pointer?
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
bool comp(int a,int b){
return a<b;
}
int main()
{
int (*p)(int,int);
p=comp;
priority_queue< int,vector<int>,decltype(&comp) > pq;
decltype(p) a;
cout<<typeid(a).name();
}
So,if it just accepts the typename, how will it have access over my compare function when it will implement its operations if it just accept typename and not actual function pointer?
There are two options for you.
Make a class, that can be constructed which has this function as a call operator.
struct comparator {
bool operator()(int a, int b) { return comp(a, b); }
};
Then use like you written, pass only the typename:
priority_queue< int,vector<int>,comparator > pq;
Pass a reference to your object (which may be a function pointer). So no need for constructing your object again:
priority_queue< int,vector<int>,decltype(p) > pq(p)
Where p is the function pointer you made before.
bool (*p)(int,int);
p=comp;
priority_queue< int,vector<int>,decltype(p) > pq(p);
Check the constructors of the priority_queue
class.