递归 stl 映射
Posted
技术标签:
【中文标题】递归 stl 映射【英文标题】:recursive stl map 【发布时间】:2010-10-15 09:25:11 【问题描述】:我正在尝试制作一棵地图树(或者只是让地图的值指向另一张地图),但我不太确定如何解决这个问题。我发现了一个关于这个的讨论:http://bytes.com/topic/c/answers/131310-how-build-recursive-map 但我对那里发生的事情有点困惑。
例如,我的键是一个字符,我的值是下一张地图。这是假设的声明:
map< char, map< char, map< char.......>>>>>>>>>> root_map;
【问题讨论】:
你的树的深度是否已知且固定? 您有问题吗? 基本上你做错了。或者可能是您的问题的错误方法。在这里先解释你的问题陈述是什么,而不是你解决问题的方法 在您引用的讨论中,他们通过禁用编译器所做的类型检查来“解决”问题。他们告诉编译器,每个映射都将一个指向未知类型的指针作为值存储,只有程序员知道它应该是指向另一个映射的指针。 感谢您的解释。我发这个的时候有点晚了,所以我猜它措辞不好。 【参考方案1】:也许你在想这样的事情:
#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';
我不会真的推荐它。
【讨论】:
【参考方案2】:我不太确定您想要实现什么,但是当我听到“地图树”时,我想到了以下内容:
class NodeData
// Some stuff...
;
class TreeNode
public:
NodeData* data;
std::map<char, TreeNode*> children;
;
【讨论】:
这是我最初的方法,我最终回到了这个。原来我只是把它们链接错了......谢谢!【参考方案3】:想法是这样的:
struct CharMap
std::map<char,CharMap> map;
root_map;
并像使用它
root_map.map['a'].map['b'];
也许您可以在 CharMap 上使用额外的方法和运算符使其更加精美,从而在访问您的结构时消除对
【讨论】:
【参考方案4】:是的,你可以。但是,为了让地图做任何有用的事情,您将不得不使用方法(在本例中为 Set 和 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;
【讨论】:
以上是关于递归 stl 映射的主要内容,如果未能解决你的问题,请参考以下文章