树状结构中内存的前向保留
Forward reservation of memory in tree-like structure
如何很好地保留树状结构的记忆?假设这将由 STL 向量实现:
struct Leaf
{
int val;
};
struct Branch
{
std::vector<Leaf> leaves;
};
现在,我可以为Branch
es 的向量保留一些内存
std::vector<Branch> branches;
branches.reserve(10);
但是如何同时为leaves
保留内存(例如在构建Branch
对象期间)?
您可以考虑将整个树存储在单个数组中,可能是向量。假设您有一个结构Node
:
struct Node
{
int val;
vector<size_t> children;
};
vector<Node> tree;
然后tree[0]
是树的根。每次你想在某个节点上添加一个新分支时,比如说tree[i]
,你这样做:
tree.resize(tree.size()+1);
tree[i].children.push_back(tree.size()-1);
// you can also set the value of the new node:
tree.back().val = 123;
然后,您可以通过从任何节点(包括根节点)开始并查看其子节点来轻松遍历树。
下面是使用 DFS 遍历树的示例:
void dfs(size_t x)
{
// you can do sth here, for example:
printf("node: %d, number of children: %dn", x, tree[x].children.size());
// go deeper in the tree to the node's children:
for (size_t i=0; i<tree[x].children.size(); ++i)
dfs(tree[x].children[i]);
}
// starting DFS from the root:
dfs(0);
这样,您可以为树保留内存:
tree.reserve(100);
当您尝试为Branch
保留内存时,您保留了多少内存?它们中的每一个都包含一个std::vector
因此它的大小是可变的。
我的建议是实际构造一个填充有(空)Branch
es的向量,但同时为它们的Leaf
保留空间,如下所示:
如果为 Branch 类/结构编写内存保留构造函数:
struct Branch{
std::vector <Leaf> leaves;
Branch (int expectedL = 10){
leaves.reserve(expectedL);
}
};
然后你可以做:
std::vector<Branch> branches(10);
或
std::vector<Branch> branches(10, 42);
不完全是你要问的,但也许有帮助。
在初始化整个树(或者可能作为树的一部分)之前,制作一些指向预先初始化的空Leaf
的指针。之后,您可以从堆栈中pop
Leaf
并将其附加到特定Branch
(并用所需的值填充Leaf
......当然,那么你应该改变:std::vector<Leaf>
std::vector<Leaf*>
.
当堆栈为空时,创建另一组空Leaf
。
相关文章:
- 必须为 C++20 协程帧保留多少内存?
- 为异步发送缓冲区保留内存(提升 asio 套接字)
- 访问"std::vector"的保留但未调整大小的内存作为原始内存是否安全?
- 释放指向保留嵌套变量内存地址的结构的指针
- std::vector<std::vector<int>>:调试断言失败。C++矢量下标超出范围保留内存
- 如何在Windows和更高版本上保留内存,并将文件映射到内存中
- 结构中的C++数组指针保留内存位置,但丢失所有值
- 是否更正PInvoke签名以使用带有C#保留内存的嵌套结构
- C++ - 关闭应用程序后保留内存
- 如何在 Windows 映射程序的 DLL 之前保留内存区域?
- 需要释放具有保留内存的 c++ Do 局部变量
- (C++)循环:不保留内存的用户输入
- OpenCL:减少示例,并保留内存对象/将cuda代码转换为OpenCL
- 如何为向量的向量保留内存
- 为结构体保留内存空间时
- 如何在构造时为std::vector保留内存?
- 如何为一个非常大的筛保留内存?
- 在堆中保留内存错误
- 为什么std::deque不是一个在索引0之前保留内存的向量
- 如何判断已提交内存和保留内存中的内容