树状结构中内存的前向保留

Forward reservation of memory in tree-like structure

本文关键字:保留 内存 结构      更新时间:2023-10-16

如何很好地保留树状结构的记忆?假设这将由 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