Recursive stl card

I'm trying to create a map tree (or just have map point values ​​on 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 bit confused about what is going on there.

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

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

+3
source share
4 answers

Perhaps you are 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 would not recommend it.

+2
source

As an idea, something like this:

struct CharMap {
    std::map<char,CharMap> map;
} root_map;

and use it like

root_map.map['a'].map['b'];

, CharMap, .map .

+2

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

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

class TreeNode
{
public:
    NodeData* data;
    std::map<char, TreeNode*> children;
};
+1
source

Yes, you can. In order for the card to do something useful, you have to decorate it with methods (in this case Set and Get).

#include <map>
#include <iostream>

class Clever : public std::map <int, Clever>
{
  public:
    Clever & Set (int i) { m_i = i; return *this; }
    int Get (void) { return m_i; }

  private:
    int m_i;
};

int main (void)
{
  Clever c;
  c[0][2][3].Set(5);

  std::cout << c[0][2][3].Get() << std::endl;

  return 0;
}
0
source

Source: https://habr.com/ru/post/1769714/


All Articles