【问题标题】:How to write standard C++ iterator?如何编写标准 C++ 迭代器?
【发布时间】:2011-09-18 05:40:48
【问题描述】:

我有以下简单的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;
};

如何在图形中的所有弧上提供标准 C++ iterator(迭代顺序无关紧要)隐藏弧在图形中的存储方式?

我想使用它类似于以下:

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

我听说过boost::iterator,但我觉得它很混乱。也许有人可以提示在这种情况下如何使用它?

【问题讨论】:

  • 也许只是在Graph 中做typedef const_iterator std::map&lt;...&gt; 然后定义函数(即arcsBegin()arcsEnd())?
  • Custom Iterator in C++ 的可能重复项

标签: c++ iterator std


【解决方案1】:

如果您不想使用 boost,请查看迭代器必须提供的内容:STL documentation

否则,您可以使用boost iterator library。请参阅与您的要求非常接近的iterator_facade tutorial

【讨论】:

  • 除此之外,我发现阅读 STL 源代码很有帮助 (sgi.com/tech/stl/download.html)。具体来说,我使用上面引用的文档来找到一个类似于我正在为其编写的数据结构的迭代器(例如,我的数据结构的迭代器要求接近于 stl::list,所以我使用了文档上面在此答案中引用了 stl::list 使用的迭代器类型)。然后,我从刚刚包含的链接中读取了 std::list::iterator 源代码。希望对您有所帮助。
【解决方案2】:

创建内部有两个迭代器的类:一个在 map 上,另一个在 set 上。

每个 ++ 都应用于 set 迭代器。当它到达末尾时,递增映射迭代器并重新初始化集合迭代器。

您也可以使用 boost::iterator_facade - 它无助于实现迭代算法,但可以最大限度地减少您使迭代器与 STL 期望兼容的工作...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    • 1970-01-01
    • 2018-03-07
    • 2015-02-20
    • 2020-08-24
    相关资源
    最近更新 更多