c++尝试在自定义类中使用优先级队列,编译器抛出错误,为什么要尝试填充队列
C++ trying to use priority queue with a custom class, compiler is throwing errors why trying to populate the queue
我试图在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);
相关文章:
- C/C++编译器通常会删除重复的库吗
- boost::进程间消息队列引发错误
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- Win32编译器选项和内存分配
- MSVC多行宏编译器错误
- 静态数据成员的问题-修复链接错误会导致编译器错误
- Android NDK传感器向事件队列报告奇怪的间隔
- C++,我收到一个无法理解的编译器错误
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 在线编译器中的分段C++没有打印消息
- 按对象的特定方法按升序排列的C++优先级队列
- 使用2个键的cpp-stl::优先级队列排序不正确
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- C/C++预处理器是否可以检测一些编译器选项
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- C++错误C2600:无法定义编译器生成的特殊成员函数(必须首先在类中声明)
- 我需要知道编译器如何在cpp中使用析构函数
- 我是否需要在下一次转移时将所有权*转移回转移队列
- c++尝试在自定义类中使用优先级队列,编译器抛出错误,为什么要尝试填充队列