使用自定义比较器返回priority_queue
我有一个函数需要根据一些输入参数返回排序列表。我选择了一个 std::priority_queue
来保存此列表。
但编译器给了我一个我不认识的错误。这是我的代码:
struct DepthCompare {
bool operator()
(const struct inst *&lhs, const struct inst *&rhs) const
{
return lhs->depth < rhs->depth;
}
};
typedef priority_queue<struct inst*> HeuristicList;
HeuristicList getHeuristicList(struct BasicBlock &) {
HeuristicList ret( DepthCompare );
return ret;
}
编译器表示在 return 语句行请求从“HeuristicList (*)(DepthCompare)”转换为非标量类型“HeuristicList”。
看起来我并没有试图返回指针。出了什么问题?
I have a function that needs to return a sorted list based on some input parameters. I've selected a std::priority_queue
to hold this list.
But the compiler is giving me an error I don't recognize. Here's the code I have:
struct DepthCompare {
bool operator()
(const struct inst *&lhs, const struct inst *&rhs) const
{
return lhs->depth < rhs->depth;
}
};
typedef priority_queue<struct inst*> HeuristicList;
HeuristicList getHeuristicList(struct BasicBlock &) {
HeuristicList ret( DepthCompare );
return ret;
}
The compiler says that a conversion from 'HeuristicList (*)(DepthCompare)' to non-scalar type 'HeuristicList' requested
on the return statement's line.
It doesn't look like I'm trying to return a pointer. What's going wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你有两个问题。
要使用自定义比较器,您必须将比较器类型指定为第三个模板参数:
HeuristicList ret( DepthCompare );
被解释为函数声明,而不是变量声明,从而给出您的错误重新看到。您需要传递比较器的实例,并确保它不能被解释为函数声明:但是,由于构造函数的第一个参数是可选的,并且默认为默认构造的比较器,因此您可以简单地编写
Or,因为你只是立即返回变量,
You have two problems.
To use a custom comparator, you must specify the comparator type as the third template argument:
HeuristicList ret( DepthCompare );
is interpreted as a function declaration, rather than a variable declaration, giving the error that you're seeing. You need to pass an instance of the comparator, and make sure it can't be interpreted as a function declaration:However, since the constuctor's first argument is optional, and defaults to a default-constructed comparator, you can simply write
Or, since you're just returning the variable straight away,
请注意,比较器是priority_queue 的第三个模板参数。您必须像这样声明
priority_queue
:这假设您想要使用
vector
作为后备容器(默认)。另请注意,在比较器函子中,您希望将参数声明为对指针的 const 引用。您拥有的是对 const 指针的引用。您想要这样:
您也不需要将比较器对象的实例传递给
priority_queue
构造函数,因为默认的比较器构造函数就可以了。Note that the comparator is the third template parameter of
priority_queue
. You must declare yourpriority_queue
like such:This assumes you want to use
vector
as the backing container (default).Also note that in your comparator functor, you want to declare the parameters as const reference to a pointer. What you have is a reference to a pointer to const. You want this:
You also don't need to pass an instance of your comparator object to the
priority_queue
constructor, as the default comparator constructor will do just fine.