为什么对象属性的值在 c++ 中将其指针添加到映射后返回零
Why value of object's attribute returns zero after adding its pointer to a map in c++
所以我有这个:
//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_id
将node
添加到map
中,然后稍后使用root_id
查找它,甚至不检查它是否找到它,因此您可能会通过访问end(nodes)
获得一些未定义的行为。您需要使用相同的密钥访问地图才能获得相同的对象。
此外,当您显然需要访问node
或地图的变量时,使用no
和nos
似乎对变量有些混淆。
相关文章:
- 添加到数组指针
- 使用指针将 ASCII 值添加到整数
- C++:添加新结构时,结构指针向量中的所有元素都会更新
- 这个失败的测试是将零添加到空指针未定义的行为、编译器错误还是其他什么?
- 添加要映射的对象的唯一指针
- 向指针地址添加 20 个字节偏移量
- 是否允许向空指针添加零?
- 在对象向量中添加指针
- C++向结构添加指针
- 如何在对象的构造函数中添加(指针)到矢量
- 通过添加指针进行复制时可能出现缓存未命中
- 添加指针导致类错误,找不到重载的成员函数
- 如何使用 OutputDebugString 添加指针
- visual如何在C++中向类添加指针
- 添加指针的内容到BSTR
- 在c++中向向量添加对象vs向向量添加指针
- c++内存泄漏:在函数中添加指针,在函数外删除指针
- 向循环中的vector添加指针
- 如何在Java编程语言中添加指针
- 如何删除向量的多个添加指针