我希望能够有一个 map ,其中的值是指向 map 的指针。有点像
std::map<KeyType, const_pointer_to_this_map's_value_type>
我知道我可以使用 const void * 而不是 const_pointer_to_this_map's_value_type。
我见过循环数据类型定义的技巧,例如 https://gist.github.com/tivtag/1208331或 http://qscribble.blogspot.fr/2008/06/circular-template-references-in-c.html但我不确定它们是否以及如何应用于我的案例。
他们在那里使用自己的类(顶点和边;A 和 B),但这里 std::map 和 std::map::value_type 已经在 STL header 中定义,我不能只用组合类。
有没有办法定义上面的 map ?
最佳答案
只需将其包装在一个结构中即可。您需要为该类型命名以便能够引用它。
template<class T>
class Graph {
std::map<T, const Graph<T>*> data;
public:
// ...
};
在 C++11 中,您还可以使用带有前向声明的 typedef 模板别名来实现:
namespace {
template<class T>
struct GraphWrap {
class type;
typedef std::map<T, const typename GraphWrap<T>::type*> type;
};
}
template<class T>
using Graph = typename GraphWrap<T>::type;
当然,在这里使用 std::map
可能有点误导,因为您使用键类型参数作为容器的值类型。就像 Mooing Duck 所说的那样,您似乎正在对一个有向图建模,其中每个节点最多有一个传出边。如果你想用图表做点什么,那里有图表库——如果你在做其他事情,或者如果你只是想学习,那就是另一回事了。
关于C++,前向声明和递归数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17305158/