Unexpected result of my DFS tree (C++)(我的 DFS 树 (C++) 的意外结果)
问题描述
我已经解决了这个问题!!!我发现如果我必须使用 vector.但我不是很确定原因,有人能告诉我为什么吗?谢谢:)
I have solved this problem!!! I found that if i have to use vector<Node*> children;. But I am not very sure the reason, can someone tell me why? Thanks:)
问题:
我使用 test.cpp 生成一个树结构,如:
I use test.cpp to generate a tree structure like:
(ROOT->children).size() 的结果是 2,因为 root 有两个孩子.
The result of (ROOT->children).size() is 2, since root has two children.
((ROOT->children)[0].children).size() 的结果应该是 2,因为 的第一个孩子root 有两个孩子.但答案是0,为什么呢?这让我很困惑.
The result of ((ROOT->children)[0].children).size() should be 2, since the first child of root has two children. But the answer is 0, why? It really confuse for me.
test.cpp(此代码可在 Visual Studio 2010 中运行)
test.cpp (This code is runnable in visual studio 2010)
#include <iostream>
#include <vector>
using namespace std;
struct Node {
int len;
vector<Node> children;
Node *prev;
Node(): len(0), children(0), prev(0) {};
};
class gSpan {
public:
Node *ROOT;
Node *PREV;
void read();
void insert(int);
};
int main() {
gSpan g;
g.read();
system("pause");
}
void gSpan::read() {
int value[4] = {1, 2, 2, 1};
ROOT = new Node();
PREV = ROOT;
for(int i=0; i<4; i++) {
insert(value[i]);
}
cout << "size1: " << (ROOT->children).size() << endl; // it should output 2
cout << "size2: " << ((ROOT->children)[0].children).size() << endl; // it should output 2
system("pause");
}
void gSpan::insert(int v) {
while(v <= PREV->len)
PREV = PREV->prev;
Node *cur = new Node();
cur->len = v;
cur->prev = PREV;
PREV->children.push_back(*cur);
PREV = cur;
}
推荐答案
问题是你的 children 向量包含 Node 值而不是 Node*代码>指针.虽然您的访问正确使用了根,但它只会找到您尝试维护的子项的副本.你的所有节点也都泄露了.
The problem is that you children vector contains Node values rather than Node* pointers. While your access uses the root correctly, it finds only copies of the children you try to maintain. All of your nodes are also leaked.
您可能希望为您的孩子使用 std::vector 并在某个时候删除他们.最简单的方法可能是使用智能指针向量,例如一个 tference 计数指针,并让智能指针负责释放.
You might want to use a std::vector<Node*> for your children and delete them at some point. The easiest way is probably to use a vector of smart pointers, e.g. a teference counted pointer, and have the smart pointer take care of the release.
这篇关于我的 DFS 树 (C++) 的意外结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我的 DFS 树 (C++) 的意外结果
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
