我正试图在c++中实现一个a*搜索函数,但在优先级队列方面遇到了很多问题。从我在网上找到的例子来看,似乎只需要定义一个带有重载"()"的比较器类;然而,Visual C++编译器似乎希望为优先级队列的元素定义赋值运算符"=",否则它会生成一条错误消息:
错误C2582:"operator="功能在"节点"中不可用
其指向实现CCD_ 1库的源代码中的一行。
因此,我继续为'node'类编写一个重载的"="操作,结果发现"push"操作在某个时刻执行赋值,所以我最终得到了一个由相同的'node'对象组成的队列。
我是不是遗漏了什么?
以下是相关代码
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
,一份副本,而不是参考资料。
priority_queue<...>::push
(有效地)使用了push_heap
算法。push_heap
算法要求元素是可复制分配的。Ergo,priority_queue<...>::push
要求元素是可复制分配的。
您的问题源于存储引用,这些引用没有正确的赋值语义。当您分配它们时,它会分配引用,而不会重新绑定引用。如果您想要可重新绑定的引用,请使用指针。