Pete said:
Random access iterators can be recognized because
iterator_traits<iter>::iterator_category is
random_access_iterator_tag.
There is no such easy identification of a map iterator. It's just a
bidirectional iterator.
.... and still the library implementation can [probably] detect its
iterator type used for 'std::map's: if the iterator type is not
nested within the 'std::map' class template it is fairly easy to
detect and a special overload for the 'std::distance()' function
template can take advantage of the known structure, e.g.:
namespace std {
// ...
template <typename _K, typename _V, typename _C, typename _A>
struct _Map_iterator
{
// funny stuff dealing with the iterator
};
template <typename _K, typename _V, typename _C, typename _A>
struct map
{
typedef _Map_iterator<_K, _V, _C, _A> iterator;
};
template <typename _K, typename _V, typename _C, typename _A>
std::size_t // just a short-hand; might use iterator_traits
distance(_Map_iterator<_K, _V, _C, _A> begin,
_Map_iterator<_K, _V, _C, _A> end)
{
// do fancy ln n algorithm to determine the distance
}
}
There is no need to have special machinery for detecting the
iterators. It is actually not even a really generic algorithm
although it is a template: it just operates on a fixed data
structure and could possibly even work on a non-templatized
base class of the 'std::map's nodes which represent the links
in the tree (although I'm not sure I would realize things this
way because it sacrifices some type-safety; of course, if profiling
shows that it is indicated, I would do it).
That said, I'm not sure that any optimization of computing the
distance or moving a pointer on 'std::map's is warranted: it is
a rare use and to prepare the data structure for this would cost
some performance even if the operations are not used. Thus, people
would pay for something they don't really use. An optimization like
this might be reasonable for a special purpose map where it is
common that iterators are advanced in large step or the distance
between iterators is frequently computed.
--
<mailto:
[email protected]> <
http://www.dietmar-kuehl.de/>
<
http://www.eai-systems.com> - Efficient Artificial Intelligence
[ See
http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]