Topic: std::distance, std::advance, iterators etc:
Author: kprateek88@yahoo.com (Prateek R Karandikar)
Date: Fri, 11 Jun 2004 20:08:51 +0000 (UTC) Raw View
24.3.4:
"template<class InputIterator>
typename iterator_traits<InputIterator>::difference_type
distance(InputIterator first, InputIterator last);
Effects: Returns the number of increments *or decrements* needed to
get from first to last.
Requires: last must be reachable from first."
(Emphasis mine)
The requires clause implies that after a finite number of applications
of ++first, first==last must be true. Then why does the effects clause
confusingly(IMHO, at least) say "increments or decrements". Why not
just say "increments"? An input iterator that is not a bidirectional
iterator doesn't even support decrementing.
"template <class InputIterator, class Distance>
void advance(InputIterator& i, Distance n);
Requires: n may be negative only for random access and bidirectional
iterators.
Effects: Increments (or decrements for negative n) iterator reference
i by n."
IMHO, the effects clause seems inaccurate. Let us analyze it
carefully. It is equivalent to:
"For n>=0, increments the iterator reference i by n. For n<0,
decrements the iterator reference by n."
Agreed upto here?
Now, "decrements the iterator reference by n" is eqivalent to
"increments the iterator reference by (-n)". (mathematically, i-n is
equivalent to i+(-n)). For n<0, (-n) is +ve, so this is not what we
want.
It could have been phrased like this:
"For n>=0, increments the iterator reference i by n.
For n<0, decrements the iterator reference i by -n,"
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
To iterate is human, to recurse divine.
-L. Peter Deutsch
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]