如何编写标准 C++迭代器?
我有以下简单的 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++ < code>iterator 遍历图中的所有弧(迭代顺序无关紧要),隐藏弧在图中的存储方式?
我想像下面这样使用它:
int main() {
Graph g;
for (Graph::const_iterator it = g.arcsBegin(); it != g.arcsEnd(); ++it) {
Arc* a = *it;
}
}
我听说过 boost::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
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您不想使用 boost,请查看迭代器必须提供的内容:STL 文档。
否则,您可以使用 boost 迭代器库。请参阅 iterator_facade 教程与你所要求的非常接近。
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.
创建内部有两个迭代器的类:一个在映射上,另一个在集合上。
每个 ++ 都应用于集合迭代器。当到达末尾时,递增映射迭代器并重新初始化集合迭代器。
您还可以使用 boost::iterator_facade - 它不会帮助实现迭代算法,但会最大限度地减少您使迭代器与 STL 期望兼容的工作...
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...