我正在尝试用 C++ 实现 A* 搜索功能,但我在优先级队列方面遇到了很多麻烦。从我在网上找到的例子来看,似乎只需要定义一个重载“()”的比较器类;然而,Visual C++ 编译器似乎需要为优先级队列的元素定义赋值运算符“=”,否则它会生成一条错误消息:
error C2582: 'operator =' 函数在 'node' 中不可用
它指向源代码中的一行,该行实现了 <algorithm>
图书馆。
所以我继续为“node”类编写一个重载的“=”操作,结果发现“push”操作在某个时候进行了赋值,所以我最终得到了一个相同的“node”对象队列.
我是不是漏掉了什么?
下面是相关代码
节点.h
#include <string>
#include <ostream>
//node used in the A* search
struct node{
public:
friend void operator<<(std::ostream& o,node& n);
node(std::string& s):msg(s),gScore(0),hScore(0),parent(nullptr){};
int getHeuristics( node& n);
bool operator==(node n){return n.msg.compare(msg)?false:true;};
node& operator=(node& n){msg = n.msg;gScore = n.gScore;hScore = n.hScore; return *this;};
void setG(int g){gScore = g;}
int getG(void) {return gScore;}
int getH(void) {return hScore;}
int getOverall(void){return hScore + gScore;}
node* getParent(void){return parent;}
std::string& msg;
private:
node* parent;
int gScore;
int hScore;
};
WordLadder.c(其中的一部分;“比较器”只是以某种方式比较节点):
string apple("apple");
string shite("shite");
string germanApple("apfel");
node germanNode(germanApple);
node a(apple);
node b(shite);
a.getHeuristics(germanNode);
b.getHeuristics(germanNode);
priority_queue<node,vector<node>,comparitor> p;
p.push(a);
//cout<<b;
p.push(b);
cout<<b; //prints "apple"
最佳答案
std::string& msg;
msg = n.msg;
这就是你的问题。您需要 std::string msg
,拷贝,而不是引用。
关于c++ - 视觉 C++ 2012 : why does priority_queue require overloading of assignment operator?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18429997/