比较优先队列中的参数
Compare argument in priority queue
我正在尝试了解 stl 中的优先级队列。我的理解是第三个参数基本上是类型名(在本例中是函数指针)。所以,如果它只接受类型名,如果它只接受类型名而不是实际的函数指针,它将如何访问我的比较函数?
#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?
有两种选择。
制作一个class,可以构造出具有此功能的call operator
struct comparator {
bool operator()(int a, int b) { return comp(a, b); }
};
然后像你写的那样使用,只传递类型名:
priority_queue< int,vector<int>,comparator > pq;
传递对您的对象的引用(可能是函数指针)。因此无需再次构造您的对象:
priority_queue< int,vector<int>,decltype(p) > pq(p)
其中p是你之前做的函数指针
bool (*p)(int,int);
p=comp;
priority_queue< int,vector<int>,decltype(p) > pq(p);
检查 priority_queue
class.
的构造函数
我正在尝试了解 stl 中的优先级队列。我的理解是第三个参数基本上是类型名(在本例中是函数指针)。所以,如果它只接受类型名,如果它只接受类型名而不是实际的函数指针,它将如何访问我的比较函数?
#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?
有两种选择。
制作一个class,可以构造出具有此功能的call operator
struct comparator { bool operator()(int a, int b) { return comp(a, b); } };
然后像你写的那样使用,只传递类型名:
priority_queue< int,vector<int>,comparator > pq;
传递对您的对象的引用(可能是函数指针)。因此无需再次构造您的对象:
priority_queue< int,vector<int>,decltype(p) > pq(p)
其中p是你之前做的函数指针
bool (*p)(int,int); p=comp; priority_queue< int,vector<int>,decltype(p) > pq(p);
检查 priority_queue
class.