Reputation: 83
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
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
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 Node
s 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