yagil
yagil

Reputation: 83

In c++ there is a way to create a tree-like map that contains maps as a value?

In c++ there is a way to create a tree-like map that contains maps as a value?

map<string, map<string, map<string, map<...>>> name;

Upvotes: 0

Views: 718

Answers (2)

molbdnilo
molbdnilo

Reputation: 66441

Not to an arbitrary depth, no.
But, like most problems, you can solve it by adding a level of indirection.

For instance,

struct Tree
{
    std::map<std::string, std::optional<Tree>> children;
};

Upvotes: 3

Asteroids With Wings
Asteroids With Wings

Reputation: 17454

For arbitrary depth, you're going to need some dynamic allocation.

struct Node
{
   map<string, std::unique_ptr<Node>> children;
};

Node root;

Your bottom-most nodes will have no children.

We can't just write map<string, Node> children (even though the child Nodes will themselves be dynamically allocated within the map), because Node is "incomplete" in the definition; in a sense, that's a limitation of C++ (though you can work around this with a little more thought).

Upvotes: 3

Related Questions