简体   繁体   English

从向量获取通用的双向迭代器

[英]Obtaining a generic bidirectional iterator from a vector

Before writing a function that takes a generic bidirectional iterator I wanted to test out how it works for a vector of ints. 在编写一个采用通用双向迭代器的函数之前,我想测试一下它如何用于int向量。

vector<int> a(10,1);
iterator<bidirectional_iterator_tag, int> i = a.begin();
for (; i != a.end(); ++i) cout << *i;

This code soes not compile. 此代码不能编译。 g++ complains you cannot convert the return type of begin() to iterator<bidirectional_iterator_tag, int> and that the operators ++ and * are not defined on it. g ++抱怨您无法将begin()的返回类型转换为iterator<bidirectional_iterator_tag, int> ,并且未在其上定义运算符++* Obviously I am doing something wrong, would appreciate help. 显然我做错了,不胜感激。

Although std::iterator is a base class which eases implementation of new iterators, not all iterators are implemented using this, and not all iterators convert to this. 尽管std::iterator是一个基类,可简化新迭代器的实现,但并非所有迭代器都使用此实现,也不是所有迭代器都可以转换为此。 The only requirement for an iterator class is that it provides a given set of operations. 迭代器类的唯一要求是它提供给定的一组操作。 No class hierarchy is implied by this, and most containers ship their own iterator classes. 这并不意味着没有类层次结构,并且大多数容器都提供了自己的迭代器类。 So in this case, you should use vector<int>::iterator as the type of your iterator. 因此,在这种情况下,应使用vector<int>::iterator作为vector<int>::iterator的类型。 Or, if you are using the recent C++11 standard, you may use auto to let the compiler infer the type. 或者,如果您使用的是最新的C ++ 11标准,则可以使用auto来让编译器推断类型。

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

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