![]() |
![]() |
![]() |
|
Categories: algorithms, iterators | Component type: function |
template <class InputIterator, class Distance> void distance(InputIterator first, InputIterator last, Distance& n);
list<int> L; L.push_back(0); L.push_back(1); int n; n = 0; [2] distance(L.begin(), L.end(), n); assert(n == 2);
[1] This is the reason that distance is not defined for output iterators: it is impossible to compare two output iterators for equality.
[2] Warning: The semantics of distance is not what one might expect at first. The expression distance(f, l, n) does not store the distance from f to l in the variable n; instead, it increments n by the distance. If you want to find the distance from f to l, you must first set n to 0. Forgetting this is a common mistake.
[3] This definition may seem awkward; it would certainly be more convenient for distance to return the distance as its return value. Unfortunately, this is impossible: there is no way to declare the return type, since the return type would have to be InputIterator's return type. A technique called iterator traits (see the Iterator Tags overview) permit the more natural definition of distance, but this technique relies on a C++ feature known as partial specialization. Partial specialization is part of the C++ standard, but no compilers currently (as of September 1996) support it. Once compilers that support partial specialization become available, future releases of the STL will use iterator traits.