我正在尝试制作一棵 map 树(或者只是将 map 的值指向另一张 map ),但我不太确定如何解决这个问题。我发现了一个关于这个的讨论:http://bytes.com/topic/c/answers/131310-how-build-recursive-map 但我对那里发生的事情有点困惑。
例如,我的键是一个字符,而我的值是下一个映射。这是假设的声明:
map< char, map< char, map< char.......>>>>>>>>>> root_map;
最佳答案
也许你在想这样的事情:
#include <iostream>
#include <map>
template <typename Key, typename Value>
struct Tree
{
typedef std::map<Key, Tree> Children;
Tree& operator=(const Value& value) { value_ = value; return *this; }
Tree& operator[](const Key& key) { return children_[key]; }
Children children_;
Value value_;
friend std::ostream& operator<<(std::ostream& os, const Tree& tree)
{
os << tree.value_ << " { ";
for (typename Children::const_iterator i = tree.children_.begin();
i != tree.children_.end(); ++i)
os << i->first << " -> " << i->second << " | ";
return os << '}';
}
};
int main()
{
Tree<int, std::string> t;
t[1].children_[1] = "one,one";
t[1].children_[9] = "one,nine";
t[1] = "hmmm";
std::cout << t << '\n';
}
我真的不会推荐它。
关于c++ - 递归STL映射,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3940976/