我正在尝试使用C++实现A *寻路算法。C++向量指针问题
我有一些问题,指针......我通常会找到一个方法来避免使用它们,但现在我想我必须要使用它们。
所以我们可以说我有一个 “节点” 类(不涉及A *)来实现这样的:
class Node
{
public:
int x;
Node *parent;
Node(int _x, Node *_parent)
: x(_x), parent(_parent)
{ }
bool operator==(const Node &rhs)
{
return x == rhs.x && parent == rhs.parent;
}
};
它有一个值(在这种情况下,INT x)和父母(指针到另一个节点)用于通过父指针在节点间导航。
现在,我想要一个包含所有已经或正在考虑的节点的节点列表。它应该是这样的:
std::vector<Node> nodes;
我想,它包含指针指向节点列表内的节点列表。 声明如下:
std::vector<Node*> list;
不过,我绝对不是正确理解指针,因为我的代码将无法正常工作。 下面是我在谈论的代码:
std::vector<Node> nodes;//nodes that have been considered
std::vector<Node*> list;//pointers to nodes insided the nodes list.
Node node1(1, NULL);//create a node with a x value of 1 and no parent
Node node2(2, &node1);//create a node with a x value of 2 and node1 being its parent
nodes.push_back(node1);
list.push_back(&nodes[0]);
//so far it works
//as soon as I add node2 to nodes, the pointer in "list" points to an object with
//strange data, with a x value of -17891602 and a parent 0xfeeefeee
nodes.push_back(node2);
list.push_back(&nodes[1]);
显然存在不确定的行为怎么回事,但我不能设法看到。 有人请告诉我,我对指针缺乏理解的地方会破坏这段代码,为什么?
哇,我从来没有想过使用索引而不是指针,我一定会尝试一下,因为“节点”向量将永远不会删除元素。 – 2010-10-11 20:42:55