简体   繁体   English

如何编写标准的C ++迭代器?

[英]How to write standard C++ iterator?

I have the following simple Graph class, where for each Node , I store a set of outgoing Arcs : 我有以下简单的Graph类,其中对于每个Node ,我存储一组传出的Arcs

#include <iostream>
#include <vector>
#include <map>
#include <set>

struct Arc {
  char label;
  int targetNode;
};

struct Graph {
  std::vector<int> nodes;
  std::map< int, std::set<Arc*> > outgoingArcsPerNode;
};

How can I provide a standard C++ iterator over all the arcs in the graph (order of iteration doesn't matter) that hides how the arcs are stored in the graph? 如何在图中的所有弧上提供标准C ++ iterator (迭代次序无关紧要),隐藏弧如何存储在图中?

I would like to use it similar to the following: 我想使用它类似于以下内容:

int main() {
  Graph g;
  for (Graph::const_iterator it = g.arcsBegin(); it != g.arcsEnd(); ++it) {
    Arc* a = *it;
  }
}

I heard of boost::iterator , but I find it confusing. 我听说过boost::iterator ,但我发现它令人困惑。 Maybe someone could give a hint how to use it in this case? 也许有人可以提示如何在这种情况下使用它?

If you don't want to use boost, have a look at what iterators must provide : STL documentation . 如果您不想使用boost,请查看迭代器必须提供的内容: STL文档

Otherwise, you may use boost iterator library . 否则,您可以使用boost迭代器库 See the iterator_facade tutorial which is very close to what you're asking. 请参阅iterator_facade教程 ,该教程非常接近您的要求。

Create class which has two iterators inside: one over map and another over set. 创建内部有两个迭代器的类:一个在地图上,另一个在集合上。

Each ++ is applied to set iterator. 每个++都应用于设置迭代器。 When it reaches the end, increment map iterator and reinitialize set iterator. 当它到达结尾时,增加map迭代器并重新初始化set iterator。

Also you can use boost::iterator_facade - it will not help to implement algorithm of the iteration, but will minimize your effort on making your iterator compatible to STL expectations... 您也可以使用boost :: iterator_facade - 它将无助于实现迭代算法,但会最大限度地减少您使迭代器与STL期望兼容的努力......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM