[英]Why does this custom comparator fail in construcing std::priority_queue while it works for std::sort?
A comparator comp
was defined as below. 比较器
comp
定义如下。 It works fine with std::sort
, but fails to compile in the constructor of std::priority_queue
. 它适用于
std::sort
,但无法在std::priority_queue
的构造函数中编译。 What is the problem? 问题是什么? Thanks.
谢谢。
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
bool comp(int a, int b) { return a > b; }
int main()
{
vector<int> vec = {4, 2, 1, 3};
sort(vec.begin(), vec.end(), comp); // OK
priority_queue<int> q1(less<int>(), vec); // OK
priority_queue<int> q2(comp, vec); // Fail
return 0;
}
Error message: 错误信息:
error: no matching function for call to 'std::priority_queue<int>::priority_queue(bool (&)(int, int), std::vector<int>&)'
priority_queue<int> q2(comp, vec);
^
The type of the default comparator of std::priority_queue
is std::less<T>
where T
is the value type. std::priority_queue
的默认比较器的类型是std::less<T>
,其中T
是值类型。 You are passing something of type bool(*)(int, int)
instead. 您正在传递类型为
bool(*)(int, int)
。 std::sort()
being a function can deduce the comparator's type. 作为函数的
std::sort()
可以推导出比较器的类型。 Class types can't deduce their template arguments (yet - there us discussion in the C++ committee that a future version may have class templates whose template arguments can be deduced. 类类型不能推断出它们的模板参数(但是 - 我们在C ++委员会中讨论了未来的版本可能有类模板,其模板参数可以推导出来。
You can use 您可以使用
std::priority_queue<int, std::vector<int>, bool(*)(int, int)> q(comp);
or, avoiding a hard-to-inline function pointer: 或者,避免难以内联的函数指针:
std::priority_queue<int, std::vector<int>, std::greater<int> > q;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.