C++将具有非常相关数据的类 Tree 拆分为两个类
C++ split class Tree with a very related data into two classes
我有一个类Tree
:
class Tree {
string aboutTree;
vector<int> veryImportantInfo;
Tree* leftChild;
Tree* rightChild;
...
void veryImportantMethod() {
// change and use aboutTree
// change and use veryImportantInfo
}
};
aboutTree
和 veryImportantInfo
不是恒定的,但对于树的所有节点都是相同的,我不想在所有节点中复制它。我想要这样的东西:
class Tree {
//string aboutTree;
//vector<int> veryImportantInfo;
Tree* leftChild;
Tree* rightChild;
...
void veryImportantMethod() {
// change and use aboutTree
// change and use veryImportantInfo
}
};
class TreeWrapper {
string aboutTree;
vector<int> veryImportantInfo;
Tree root;
...
};
但是不是工作,因为我无法访问TreeWrapper
的非静态字段。
我想出的一个可能的粗略解决方案是让所有分支链接回包装器并直接访问数据:
注意我用Tree
替换了TreeWrapper
,用branch
替换了Tree
,因为这对我来说更有意义。
class tree
{
public:
struct branch
{
branch* leftChild;
branch* rightChild;
tree* parent;
void veryImportantMethod() {
// change and use parent->aboutTree
// change and use parent->veryImportantInfo
}
};
tree() { root.parent = this; }
tree root;
string aboutTree;
vector<int> veryImportantInfo;
};
每当您创建新branch
时,您都需要leftChild->parent = parent;
. 您还需要定义 branch
的成员函数来为您执行此操作,就像在双向链表中一样。
另一种解决方案是使用实际的双向链表格式。所以tree* parent
会branch* parent
. 从分支访问重要信息不会像上面那么快,但这意味着它将更易于导航。你可以更容易地绕着树走。 (实际上,同时拥有tree* root
和branch* parent
可能不是一个坏主意。但更精细的细节取决于你。
相关文章:
- C++将向量的向量拆分为向量的N个子向量
- 如何拆分文件中.txt字母并使用c ++使用数组进行扑克?
- OpenCV 4.1.2 - 从网络摄像头获取帧并将其拆分
- 使用 C++ 将命令行参数拆分为参数/向量
- C++(.cpp文件和.h文件)拆分代码并添加一个函数,提取 - 这很容易吗?
- 如何在C++中将数字拆分为数字
- 在线程之间拆分任务总是值得的吗?
- 将字符串拆分为标记,并将标记拆分为两个单独的数组
- 在 c++ 中拆分类和标头中的继承,错误
- 在矢量内拆分 deques
- 拆分重叠段
- 我还可以添加什么来按空格或空格正确拆分C++字符串?
- 通过空行提升拆分字符串
- 给定一个大小为 N 的数组 S,检查是否可以将序列拆分为两个序列
- 如何按多个括号类型拆分字符串,但仍将括号保留在C++?
- 将 Boost.Spirit.X3 解析器拆分为多个 TU
- 使用 boost::p roperty_tree::p tree 如何获取特定键的值
- 将字符串拆分为等长 c++ 的部分
- 将执行循环拆分为多个线程 (1-N-1-N-1..)
- C++将具有非常相关数据的类 Tree 拆分为两个类