C++ Standard Library C++ STL Library

C++ - <iterator>



C++ <iterator>

An iterator is an object that points to some element in a given range of elements (for example - an element of an array or a container). It has the ability to traverse from one element to another element in that range. It is a pointer-like object that can be incremented with ++, dereferenced with *, and compared against another iterator with !=. The main advantage of using an iterator is that it provides a common interface for all the containers type.

Iterator categories

Until C++17, there are five kinds of iterators. Since C++17, there are six kinds of iterators.

  1. InputIterator
  2. OutputIterator
  3. ForwardIterator
  4. BidirectionalIterator
  5. RandomAccessIterator
  6. ContiguousIterator (since C++17)

The properties of each iterator category are given below:

CategoryPropertiesValid
Expressions
All categoriescopy-constructible, copy-assignable and destructibleX b(a);
b = a;
Can be incremented++a
a++
ContiguousRandom AccessBidirectionalForwardInputSupports equality/inequality comparisonsa == b
a != b
Can be dereferenced as an rvalue*a
a->m
OutputCan be dereferenced as an lvalue
(only for mutable iterator types)
*a = t
*a++ = t
default-constructibleX a;
X()
Multi-pass: neither dereferencing nor incrementing affects dereferenceability{b=a; *a++; *b;}
Can be decremented--a
a--
*a--
Supports arithmetic operators + and -a + n
n + a
a - n
a - b
Supports inequality comparisons (<, >, <= and >=) between iteratorsa < b
a > b
a <= b
a >= b
Supports compound assignment operations += and -=a += n
a -= n
Supports offset dereference operator ([])a[n]
Supports contiguous storage

C++ <iterator> - Non-member Functions

These non-member functions provide a generic interface for containers, arrays and <initializer_list>.

Range Access

FunctionsDescription
begin() Returns iterator pointing to the first element of the iterator.
end() Returns iterator pointing to the past-the-last element of the iterator.
rbegin() Returns reverse iterator to the last element of the iterator.
rend() Returns reverse iterator to the element preceding the first element of the iterator.
cbegin() Returns const_iterator pointing to the first element of the iterator.
cend() Returns const_iterator pointing to the past-the-last element of the iterator.
crbegin() Returns const_reverse_iterator to the last element of the iterator.
crend() Returns const_reverse_iterator to the element preceding the first element of the iterator.