c++ - priority_queue 常量表达式

标签 c++ priority-queue

代码如下:

比较算法

class PathComp{
public:
virtual bool betterThan(const PathInfo& path1, const PathInfo& path2) const{
//returns true if path1 is shorther than path2
{
};

重新定义运算符 () 的类

class QueueComp{
private:
PathComp* comp;
public:
QueueComp(PathComp* pc);
bool operator () (const pair<PathInfo, string>& item1, const pair<PathInfo, string> item2);
};

QueueComp::QueueComp(PathComp* pc):comp(pc){}
bool QueueComp::operator () (const pair<PathInfo, string>& item1, const pair<PathInfo, string>& item2){
    return comp->betterThan(item1.first, item2.first);
}

使用优先队列的函数

list<string> Graph::shortestPath(const string& from, const string& to, PathComp* pc) const{
    const QueueComp comp(pc);
    std::priority_queue<pair<PathInfo, string>, set<pair<PathInfo, string> >, comp> q;
}

编译器显示错误消息:“comp”不能出现在常量表达式中, 模板参数 3 无效, 之前声明中的无效类型; token

有人知道问题出在哪里吗?感谢所有帮助。

最佳答案

编译器已经说明了问题所在:一个非 constexpr不能是模板参数。你可能打算写

std::priority_queue<std::pair<PathInfo, std::string>,
                    std::vector<std::pair<PathInfo, std::string> >,
                    QueueComp>
    q(comp);

眼前的问题是 comp是一个对象,但模板需要比较函数的类型。一旦解决了这个问题,下一个问题就是 std::set<...>不是与 std::priorit_queue<...> 一起使用的可行容器但是std::vector<...>是。

关于c++ - priority_queue 常量表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13555522/

相关文章:

c++ - 如何用cout打印函数指针?

c++ - 是否有可能在构造函数和析构函数之外修改 `vptr`?

c++ - STL 堆栈和 priority_queue 的插入器

c++ - 多类C++的优先级队列

javascript - 深拷贝 NAPI::Value 对象

c++ - 有死胡同的汽车经销店 - 无休止的循环,没有解决方案

c++ - 在二维数组中添加列

c++ - 如何在 std::priority_queue 的仿函数中传输附加对象?

java - 在 Java 中排序优先级队列

algorithm - 为什么 Dijkstra 算法中的 decreasekey 需要 O(logN) 时间?