返回一个“任何种类的输入迭代器”,而不是一个vector :: iterator或一个list :: iterator [英] Returning an 'any kind of input iterator' instead of a vector::iterator or a list::iterator
问题描述
假设我想在C ++中实现一个数据结构来存储定向图。由于STL容器,弧将被存储在节点中。我希望用户能够以类似STL的方式遍历一个节点的弧线。
Suppose I want to implement in C++ a data-structure to store oriented graphs. Arcs will be stored in Nodes thanks to STL containers. I'd like users to be able to iterate over the arcs of a node, in an STL-like way.
我所遇到的问题是我不想在Node类(实际上是一个抽象基类)中公开哪个STL容器将在具体类中实际使用。因此我不想让我的方法返回std :: list :: iterator或std :: vector :: iterator ...
The issue I have is that I don't want to expose in the Node class (that will actually be an abstract base class) which STL container I will actually use in the concrete class. I therefore don't want to have my methods return std::list::iterator or std::vector::iterator...
我试过这个:
class Arc;
typedef std::iterator<std::random_access_iterator_tag, Arc*> ArcIterator; // Wrong!
class Node {
public:
ArcIterator incomingArcsBegin() const {
return _incomingArcs.begin();
}
private:
std::vector<Arc*> _incomingArcs;
};
但这不正确,因为vector :: const_iterator不能用于创建ArcIterator。那么这个ArcIterator可以是什么呢?
But this is not correct because a vector::const_iterator can't be used to create an ArcIterator. So what can be this ArcIterator?
我发现这篇文章关于 STL的自定义迭代器,但它没有帮助。我今天必须有点沉重...;)
I found this paper about Custom Iterators for the STL but it did not help. I must be a bit heavy today... ;)
推荐答案
尝试:
class Arc;
class Node {
private:
std::vector<Arc*> incoming_;
public:
typedef std::vector<Arc*>::iterator iterator;
iterator incoming_arcs_begin()
{ return incoming_.begin(); }
};
并在其余代码中使用Node :: iterator。当/如果更改容器,您必须在一个地方更改typedef。 (你可以进一步用额外的typedef为存储,在这种情况下的向量。)
And use Node::iterator in the rest of the code. When/if you change the container, you have to change the typedef in a single place. (You could take this one step further with additional typedef for the storage, in this case vector.)
进一步。对于const问题,要么定义向量的const_iterator是你的迭代器,或者像向量一样定义双重迭代器类型(const和非const版本)。
As for the const issue, either define vector's const_iterator to be your iterator, or define double iterator types (const and non-const version) as vector does.
这篇关于返回一个“任何种类的输入迭代器”,而不是一个vector :: iterator或一个list :: iterator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!