简体   繁体   中英

C++ Data Structure for Nested Number Lists

I need an efficient C++ implementation of a data structure that can store nested lists of numbers, such as:

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

I want to be able to loop over the deepest elements in a very efficient manner, so that I can access sets of three numbers in this order that they appear in the nested list:

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

I also wish to add elements to the tree by passing a set of three numbers and having the appropriate numbers added to each level of the tree. I believe that I should use some type of tree data structure for this, but do not know which one would be most efficient.

Finally, I want to associate a value with each "leaf", so each triple will map to some integer value.

A Trie is likely to be the most efficient structure for something like this. You can find an overview on what Trie's are here .

Essentially Trie's store values where there are liable to be many overlaps early in the values (like strings or sequences of numbers), by only storing each value at each position once. The diagram you drew almost exactly depicts a Trie.

It's hard to tell exactly what you want.

A quick solution would just be a std::map<std::tuple<int, int, int>, ValueType> , where in your example the ValueType would just be int .

Alternatively, you could do something like this:

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
}

It's very like to suffix trees . But which one is more convenient for you.. solve you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM