STL 映射到自身?

2022-01-24 00:00:00 containers c++ map stl

我想创建一个 std::map,其中包含一个 std::vector 迭代器,以实现一个简单的基于邻接列表的图形结构.

但是,类型声明让我很困惑:您似乎需要整个映射类型定义来获取所述映射的迭代器类型,如下所示:

地图

int, 东西 >::iterator MyMap_it;//Something 应该是什么?地图

是否有某种部分映射迭代器类型我可以只使用键类型来获得,所以我可以声明完整映射?

解决方案

你可以使用新类型的前向声明.

类 MapItContainers;typedef map::iterator MyMap_it;类 MapItContainers{上市:矢量<MyMap_it>向量;};

使用这种间接方式,编译器应该可以让你摆脱它.它不是很漂亮,但老实说,我认为你不能轻易打破自我引用.

I'd like to create a std::map that contains a std::vector of iterators into itself, to implement a simple adjacency list-based graph structure.

However, the type declaration has me stumped: it would seem you need the entire map type definition to get the iterator type of said map, like so:

map< int, Something >::iterator MyMap_it;  // what should Something be?
map< int, vector<MyMap_it> > MyMap_t;

Is there some sort of partial map iterator type I can get with just the key type, so I can declare the full map?

解决方案

You could use forward declaration of a new type.

class MapItContainers;
typedef map<int, MapItContainers>::iterator MyMap_it;

class MapItContainers
{
public:
 vector<MyMap_it> vec;
};

With this indirection the compiler should let you get away with it. It is not so very pretty but honestly I don't think you can break the self referencing easily.

相关文章