std :: priority_queue:不定义比较器类的自定义排序

std :: priority_queue:不定义比较器类的自定义排序

问题描述:

我想要自定义排序的优先级队列,但因为我很懒,所以我不想定义一个实现operator()的比较器类。std :: priority_queue:不定义比较器类的自定义排序

我真的想这样的编译:

std::priority_queue<int, std::vector<int>, 
    boost::bind(some_function, _1, _2, obj1, obj2)> queue; 

其中some_function是一个布尔返回函数需要四个参数,队列的第一个和第二个是整数,这两个最后的一些物品需要用于计算排序(常量引用)。

(error: ‘boost::bind’ cannot appear in a constant-expression)

但是这不能编译。即使更简单

std::priority_queue<int, std::vector<int>, &compare> queue; 

不会编译,比较是一个返回布尔值的二进制函数。

(error: type/value mismatch at argument 3 in template parameter list for ‘template class std::priority_queue’; expected a type, got ‘compare’)

有什么建议吗?

+0

在这里'boost :: bind'上没有关闭paren - 在队列模板参数>之前。这是发布代码中的错字还是您尝试编译的内容? – 2010-11-15 16:48:19

这可能工作:

std::priority_queue<int, std::vector<int>, 
    boost::function<bool(int,int)> > 

然后在你的绑定表达式到队列的构造函数传递。

P.S.你会得到那些编译错误,因为你在运行时评估的表达式中需要一个类型名或常量表达式。

+3

+1,这是一个很好的解决方案。不幸的是,这与静态提供特定模板函数/函数参数不完全相同,因为'boost :: function'使用动态分配来创建可变函数对象。因此,您将不会获得与使用静态提供的自定义函数参数相同的编译器生成的内联效率。 – 2010-11-15 16:51:44

+0

@Charles:这很好。 – 2010-11-15 17:06:05