Re: Declaring iterators
On Apr 28, 8:22 pm, desktop <f...@sss.com> wrote:
I am not sure I quite understand the use of iterators. I have this int
array:
int a[] = {1,2,3,4,5}
I would now like to make an iterator to the first and last element:
std::iterator<int> iter;
iter = a;
but this does not compile.
Obviously. The template std::iterator requires two arguments,
and doesn't do what you want anyway. (Despite its name, it
isn't an iterator, but simply a convenience class to provide a
certain number of useful typedef's for any iterator you might
choose to define.)
If I instead choose to make an iterator on a vector it works:
#include <vector>
std::vector<int> vecIter;
why is it not possible to make an iterator to an int array (besides from
the obvious: int* iter = a)?
Are you saying that if you include <vector>, the line:
std::iterator< int > iter ;
compiles? It shouldn't.
Each container type provides its own iterator. Containers in
the STL provide it as a member type (or typedef), e.g.:
std::vector< int >::iterator iter = v.begin();
C style arrays provide it in the form of a pointer; the
constraints on iterators were intentionally designed so that
pointers (into an array) would be iterators. The result is that
you do declare the iterators differently:
std::vector< int >::iterator iter1 ;
int* iter2 ;
What's the problem with that?
--
James Kanze (Gabi Software) email: james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34