Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtaining a generic bidirectional iterator from a vector

Tags:

c++

iterator

stl

Before writing a function that takes a generic bidirectional iterator I wanted to test out how it works for a vector of ints.

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. Obviously I am doing something wrong, would appreciate help.

like image 899
san Avatar asked Jul 18 '12 19:07

san


1 Answers

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. 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. Or, if you are using the recent C++11 standard, you may use auto to let the compiler infer the type.

like image 128
MvG Avatar answered Sep 23 '22 01:09

MvG