Re: a few questions about iterators
On Jul 6, 12:23 pm, Jess <w...@hotmail.com> wrote:
Hello,
Iterators are typically put into five different categories, namely
input iterator, output iterator, forward iterator, bidirectional
iterator and random iterator. The differences come from the
requirements each kind of iterator has to meet. Therefore, I think
the five categories are kind of conceptual thing, i.e. they are not
really C++ structs/classes etc, is this correct?
They are C++ classes, thats why a code like
vector<int> v;
vector<int>::iterator s = v.begin();
compiles
There are some functions that return iterators. For example, the
"back_inserter" function returns an iterator when given a container.
Is the returned iterator an object of class type?
Yeah, back_inserter() returns a back_insert_iterator for the container
for which it is invoked.
template <class C> back_insert_iterator<C> back_inserter (C& x)
For this particular
function, is the returned iterator a forward iterator only, or is it
random access iterator?
The returned iteator is a back_insert_iterator which is an adaptor
that functions as output iterator.
Another question is that if I implement a container, which has a
function "end()", then it should return one past the last element.
However, the one past element isn't in the container, if the "end()"
is
iterator end(){
return begin() + size();}
then the result may be a pointer pointing to some other structure. On
one hand, it looks a bit unsafe, hence I should reserve the last
element in my container (and not store any real value at that
position) to represent the one-past. On the other hand, since
deferencing an iterator to "end()" is undefined, perhaps I can just
return "begin()+size()". Which strategy is better?
C++ guarantees that you can have an iterator to one-past-last element
of a container. Dereferencing such an itertaor is not allowed however.
Thanks,
Jess