views:

69

answers:

3

I'm trying to make a tree of maps (or just have values of a map point to another map), but I'm not too sure how to approach this. I found a discussion about this: http://bytes.com/topic/c/answers/131310-how-build-recursive-map but I'm a little confused on what's going on there.

For example, my key is a char, and my value is the next map. Here's the hypothetical declaration:

map< char, map< char, map< char.......>>>>>>>>>> root_map;

A: 

Maybe you're thinking of something like:

#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';
}

I wouldn't really recommend it.

Tony
A: 

Take a look at this question http://stackoverflow.com/questions/205945

pkit
A: 

I'm not excatly sure what you want to achieve, but when I hear "tree of maps" I think of the following:

class NodeData
{
    // Some stuff...
};

class TreeNode
{
public:
    NodeData* data;
    std::map<char, TreeNode*> children;
};
Sebastian N.
This was my original approach, and I ended up going back to this. Turns out I was just linking them wrong...thanks!
thomast.sang