c++ - 视觉 C++ 2012 : why does priority_queue require overloading of assignment operator?

标签 c++ visual-c++

我正在尝试用 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/

相关文章:

c++ - 我正在尝试加载模型但未显示

C++ 转换为基数和 "overwriting"vptr 问题

c++ - 从 Visual C++ 移植到 Borland C++ Builder 的 ActiveX 代码

c++ - 具有不同参数的同名宏

c++ - 如何在 Windows 上找到 Qt5 CMake 模块

c++ - 为什么输出不是预期的那样?

c++ - 体系结构 x86_64 : Compiling in C++ 的 undefined symbol

c++ - 使用 std::stringstream 读取/写入无符号字节

c++ - QT/C++ Commit a value to other class

c++:在函数参数列表中使用或不使用 namespace