递归STL映射

tho*_*ang 5 c++ recursion dictionary stl

我正在尝试制作一棵地图树(或者只是将一个地图的值指向另一个地图),但我不太确定如何解决这个问题。我找到了关于此的讨论:http://bytes.com/topic/c/answers/131310-how-build-recursive-map但我对那里发生的事情有点困惑。

例如,我的键是一个字符,我的值是下一个地图。这是假设的声明:

map< char, map< char, map< char.......>>>>>>>>>> root_map;
Run Code Online (Sandbox Code Playgroud)

Ton*_*roy 2

也许你正在想这样的事情:

#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';
}
Run Code Online (Sandbox Code Playgroud)

我真的不会推荐它。