简体   繁体   中英

How to declare a nested unordered_map where type of the value is the same of the unordered_map?

I would like to know if it's possible to declare a type, T , that is unordered_map<char, T> , where the type of the value of the unordered_map is also T , to form a tree-like structure with variable number of children.

Basically, I'm thinking about something functionaljy equivalent to using the following but without defining a structure like Node below:

//Node of a tree
struct Node {
   char val;
   unordered_map<char, Node*> children;
};

Seemingly, this would require me to declare a multi-level map with unknown levels. Is this possible?

unordered_map<char, unordered_map<char, unordered_map<char, unordered_map<char, ...

Is there anything in C++ (maybe with std::any and std::any_cast ) that could solve issue above similar to Java's Map<char, Object> , where the value type Object itself is also Map<char, Object> ?

See https://godbolt.org/z/rKaGE14qe .

It compiles with gcc 12.1, but in gcc 11.3, it will not compile. In fact, unordered_map can support incomplete types, because the initialization of unordered_map doesn't need to create a value_type object. However, it's undefined behavior as of now.

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