开发者

How to write standard C++ iterator?

I have the following simple Graph class, where for each Node, I store a set of outgoing 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 开发者_JAVA技巧over all the arcs in the graph (order of iteration doesn't matter) that hides how the arcs are stored in the graph?

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. 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.

Otherwise, you may use boost iterator library. See the iterator_facade tutorial which is very close to what you're asking.


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.

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...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜