gpt4 book ai didi

C++ 指针 vector 问题

转载 作者:行者123 更新时间:2023-11-30 00:59:41 25 4
gpt4 key购买 nike

我目前正在尝试使用 C++ 实现 A* 寻路算法。

我在指针方面遇到了一些问题...我通常会找到一种方法来避免使用它们,但现在我想我必须使用它们。

假设我有一个“节点”类(与 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;

我想要一个包含指向 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]);

显然存在未定义的行为,但我无法看出发生在哪里。有人可以告诉我我对指针缺乏理解在哪里破坏了这段代码以及为什么吗?

最佳答案

因此,您遇到的第一个问题是您正在使用其中一个 vector 的各个节点的地址。但是,随着时间的推移,当您向 vector 中添加更多 Node 对象时,这些指针可能会变得无效,因为 vector 可能会移动节点。

( vector 以某个预先分配的大小开始,当您填满它时,它会分配一个新的、更大的存储区域,并将所有元素移动到新位置。我敢打赌,在您的情况下,一旦将第二个节点添加到节点,它就会执行此操作。)

是否有原因导致您无法存储索引而不是原始指针?

关于C++ 指针 vector 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3909711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com