嵌套数字列表的c++数据结构

C++ Data Structure for Nested Number Lists

本文关键字:c++ 数据结构 列表 数字 嵌套      更新时间:2023-10-16

我需要一个有效的c++数据结构实现,可以存储嵌套的数字列表,例如:

0: 
   1: 
      3
      4
      7
   5: 
      10
      13
      15
   7: 
      2
1:
   1: 
       2
       3
   6: 
       7
       9

我希望能够以一种非常有效的方式循环遍历最深处的元素,这样我就可以按照它们在嵌套列表中出现的顺序访问由三个数字组成的集合:

(0,1,3)
(0,1,4)
(0,5,10)
...

我还希望通过传递一组三个数字并在树的每一层添加适当的数字来向树添加元素。我认为我应该使用某种类型的树数据结构,但不知道哪种是最有效的。

最后,我想将一个值与每个"叶子"关联起来,这样每个三元组将映射到某个整数值。

对于这种情况,Trie可能是最有效的结构。你可以在这里找到关于Trie的概述。

本质上,Trie的存储值可能在值的早期有很多重叠(如字符串或数字序列),每个值只在每个位置存储一次。

很难说你到底想要什么。

一个快速的解决方案就是std::map<std::tuple<int, int, int>, ValueType>,而在你的例子中,ValueType就是int

或者,您可以这样做:

class Node
{
    //optional - depends on whether you need it:
    std::weak_ptr<Node> parent;
    //for the children, you might want this (if they are numbered 0, 1, ...)
    std::vector<std::unique_ptr<Node>> children;
    //or instead you might want this for the children
    //(if they are numbered with potential gaps, like in your example):
    std::map<int, std::unique_ptr<Node>> children;
};
class LeafNode : Node
{
    ValueType data; //ValueType is whatever you want
}

这很像给树加上后缀。但是哪一个对你更方便…解决你。