代码如下:
比较算法
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/