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.
- InputIterator
- OutputIterator
- ForwardIterator
- BidirectionalIterator
- RandomAccessIterator
- ContiguousIterator (since C++17)
The properties of each iterator category are given below:
Category | Properties | Valid Expressions | ||||
---|---|---|---|---|---|---|
All categories | copy-constructible, copy-assignable and destructible | X b(a); b = a; | ||||
Can be incremented | ++a a++ | |||||
Contiguous | Random Access | Bidirectional | Forward | Input | Supports equality/inequality comparisons | a == b a != b |
Can be dereferenced as an rvalue | *a a->m | |||||
Output | Can be dereferenced as an lvalue (only for mutable iterator types) | *a = t *a++ = t | ||||
default-constructible | X 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 iterators | a < 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
Functions | Description |
---|---|
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. |