c++尝试在自定义类中使用优先级队列,编译器抛出错误,为什么要尝试填充队列



我试图在c++中创建一个二维整数数组的A*搜索(我对c++非常陌生,但我已经在Java中做了很多次)问题是,当我试图将项目推入队列时,它会由于类型冲突而抛出编译错误。

My Node.h定义为:

class Node{
private:
    int xCoord;
    int yCoord;
    int value;
    Node* parent;
public:
    Node();
    Node(int x, int y, int value);
    void setParent(Node* parent);
    int getX();
    int getY();
    int getValue();
    Node* getParent();
    bool operator()(Node& node1, Node& node2);
};
struct NodeCompare {
    bool operator()(Node& node1, Node& node2) const
    {
        int node1value = node1.getValue();
        int node2value = node2.getValue();
        return node1value < node2value;
    }
};

Node.cpp:

#include <stdlib.h>
#include "Node.h"
Node::Node(){
    this->xCoord = -1;
    this->yCoord = -1;
    this->value = -1;
    this->parent = NULL;
}
Node::Node(int _x, int _y, int _value){
    this->xCoord = _x;
    this->yCoord = _y;
    this->value = _value;
    this->parent = NULL;
}
void Node::setParent(Node* par){
    this->parent = par;
}
int Node::getX(){
    return xCoord;
}
int Node::getY(){
    return yCoord;
}
int Node::getValue(){
    return value;
}
Node* Node::getParent(){
    return parent;
}

bool节点::操作符()(Node&node1 Node&node2) {

return node1.value > node2.value;

}

和my main:

#include <iostream>
#include <ostream>
#include <vector>
#include <queue>
#include "Node.h"
int main(){
    using namespace std;
    priority_queue<Node, vector<Node>, NodeCompare> openList;
    Node* node = new Node(1,2,19);
    openList.push(node);
    cout << "node is: x " << node->getX() << " y " << node->getY() << " value "
            << node->getValue() << endl;

    return 0;
}

编译器说:

error: no matching function for call to ‘std::priority_queue<Node, std::vector<Node>, NodeCompare>::push(Node*&)’

这是与节点的类型,我试图推到列表(所以我相信)我已经尝试改变我的代码如下:

Node node = new Node(1,2,19);

给出错误:

error: conversion from ‘Node*’ to non-scalar type ‘Node’ requested

,我试着把我知道的所有变化都传进去:

openList.push(&node);

openList.push(*node);

但是它们也会抛出编译错误。

有人能解释一下我做错了什么吗?

欢呼,克里斯。

new返回一个指向对象的指针,而您的优先级队列被声明为持有实际的对象。你可以这样改变main来处理Node对象,而不是指向堆上的Node的指针:

int main(){
    using namespace std;
    priority_queue<Node, vector<Node>, NodeCompare> openList;
    Node node = Node(1,2,19);
    openList.push(node);
    cout << "node is: x " << node.getX() << " y " << node.getY() << " value "
            << node.getValue() << endl;

    return 0;
}

您正在尝试向节点对象列表添加节点指针。我推荐的是openList.push(*node);

最新更新