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++) 的意外结果
基础教程推荐
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01