class template
<iterator>

std::iterator_traits

template <class Iterator> class iterator_traits;template <class T> class iterator_traits<T*>;template <class T> class iterator_traits<const T*>;
Iterator traits
Traits class defining properties of iterators.

Standard algorithms determine certain properties of the iterators passed to them and the range they represent by using the members of the corresponding iterator_traits instantiation.

For every iterator type, a corresponding specialization of iterator_traits class template shall be defined, with at least the following member types defined:

memberdescription
difference_typeType to express the result of subtracting one iterator from another.
value_typeThe type of the element the iterator can point to.
pointerThe type of a pointer to an element the iterator can point to.
referenceThe type of a reference to an element the iterator can point to.
iterator_categoryThe iterator category. It can be one of these:

Note: For output iterators that are not at least forward iterators, any of these member types (except for iterator_category) may be defined as void.

The iterator_traits class template comes with a default definition that obtains these types from the iterator type itself (see below). It is also specialized for pointers (T*) and pointers to const (const T*).

Note that any custom class will have a valid instantiation of iterator_traits if it publicly inherits the base class std::iterator.

Member types

membergeneric definitionT* specializationconst T* specialization
difference_typeIterator::difference_typeptrdiff_tptrdiff_t
value_typeIterator::value_typeTT
pointerIterator::pointerT*const T*
referenceIterator::referenceT&const T&
iterator_categoryIterator::iterator_categoryrandom_access_iterator_tagrandom_access_iterator_tag

Example

1
2
3
4
5
6
7
8
9
10
11
// iterator_traits example
#include <iostream>     // std::cout
#include <iterator>     // std::iterator_traits
#include <typeinfo>     // typeid

int main() {
  typedef std::iterator_traits<int*> traits;
  if (typeid(traits::iterator_category)==typeid(std::random_access_iterator_tag))
    std::cout << "int* is a random-access iterator";
  return 0;
}

Output:

int* is a random-access iterator


See also