为什么对象属性的值在 c++ 中将其指针添加到映射后返回零

Why value of object's attribute returns zero after adding its pointer to a map in c++

本文关键字:添加 指针 映射 返回 属性 对象 c++ 为什么      更新时间:2023-10-16

所以我有这个:

//sons is an attribute of the object node that is a vector<Node*> that is initialized before
map<string,Node*> nodes;
string node_id = "node";
string son_id = "son";
Node *node = new Node(node_id, matrix, son_id, Prim);
cout << "Before " << node << endl;
cout << "Value of sons before map: " << node->sons[0] << endl;
nodes[node_id] = node;
cout << "After: " << nodes.find(node_id)->second << endl;
cout << "Value of sons after map: " << nodes.find(node_id)->second->sons[0];

我得到了这个输出(从执行到执行的内存位置不同):

Before: 0x9dfdda8
Value of sons before map: 0xbff1a774 // consistant with memory position with created obj
After: 0x9dfdda8
Value of sons after map: 0

为什么会发生这种情况,我该如何解决?!我一直在寻找解决方案并试图解决这个问题 4 个小时......

cout << "After: " << nodes.find(root_id)->second << endl;
cout << "Value of sons after map: " << nos.find(root_id)->second->sons[0];

为什么第二行指的是nos,第一行指的是nodes?只是错别字吗?

如果这些对象确实不同,那也许可以解释为什么你会看到不一致的结果。

您使用键node_idnode添加到map中,然后稍后使用root_id查找它,甚至不检查它是否找到它,因此您可能会通过访问end(nodes)获得一些未定义的行为。您需要使用相同的密钥访问地图才能获得相同的对象。

此外,当您显然需要访问node或地图的变量时,使用nonos似乎对变量有些混淆。