【问题标题】:C++ Data Structure for Nested Number Lists嵌套数字列表的 C++ 数据结构
【发布时间】:2013-06-06 23:13:19
【问题描述】:

我需要一个可以存储嵌套数字列表的数据结构的高效 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)
...

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

最后,我想为每个“叶子”关联一个值,所以每个三元组都会映射到某个整数值。

【问题讨论】:

  • 看起来像一棵二叉树
  • 很抱歉,他们可以在任何级别拥有超过 2 个孩子...

标签: c++ data-structures


【解决方案1】:

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

本质上,Trie 将值存储在值的早期可能有许多重叠的地方(如字符串或数字序列),只需将每个值存储在每个位置一次。您绘制的图表几乎完全描绘了一个 Trie。

【讨论】:

  • 谢谢。鉴于我需要按顺序迭代元素,看来 Trie 是最合适的。
【解决方案2】:

很难准确地说出你想要什么。

一个快速的解决方案就是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
}

【讨论】:

  • 我想基于地图的实现将是最简单的......它只需要为数字键存储大约三倍的数据
  • @SamManzer “快速解决方案...” - 根据 OP 的应用程序,他可能根本不担心内存使用情况。如果是的话,可以使用更高级的东西。
【解决方案3】:

很喜欢suffix trees。但是哪一个更方便你..解决你。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2019-03-22
    • 2014-04-27
    • 2018-03-16
    • 1970-01-01
    • 2020-01-31
    • 2018-07-21
    相关资源
    最近更新 更多