Iterators

suggest change

Iterators are Positions

Iterators are a means of navigating and operating on a sequence of elements and are a generalized extension of pointers. Conceptually it is important to remember that iterators are positions, not elements. For example, take the following sequence:

A B C

The sequence contains three elements and four positions

+---+---+---+---+
| A | B | C |   |
+---+---+---+---+

Elements are things within a sequence. Positions are places where meaningful operations can happen to the sequence. For example, one inserts into a position, before or after element A, not into an element. Even deletion of an element (erase(A)) is done by first finding its position, then deleting it.

From Iterators to Values

To convert from a position to a value, an iterator is dereferenced:

auto my_iterator = my_vector.begin(); // position
auto my_value = *my_iterator; // value

One can think of an iterator as dereferencing to the value it refers to in the sequence. This is especially useful in understanding why you should never dereference the end() iterator in a sequence:

+---+---+---+---+
| A | B | C |   |
+---+---+---+---+
  ↑           ↑
  |           +-- An iterator here has no value. Do not dereference it!
  +-------------- An iterator here dereferences to the value A.

In all the sequences and containers found in the C++ standard library, begin() will return an iterator to the first position, and end() will return an iterator to one past the last position (not the last position!). Consequently, the names of these iterators in algorithms are oftentimes labelled first and last:

+---+---+---+---+
| A | B | C |   |
+---+---+---+---+
  ↑           ↑
  |           |
  +- first    +- last

It is also possible to obtain an iterator to any sequence, because even an empty sequence contains at least one position:

+---+
|   |
+---+

In an empty sequence, begin() and end() will be the same position, and neither can be dereferenced:

+---+
|   |
+---+
  ↑
  |
  +- empty_sequence.begin()
  |
  +- empty_sequence.end()

The alternative visualization of iterators is that they mark the positions between elements:

+---+---+---+
| A | B | C |
+---+---+---+
↑   ^   ^   ↑
|           |
+- first    +- last

and dereferencing an iterator returns a reference to the element coming after the iterator. Some situations where this view is particularly useful are:

Invalid Iterators

An iterator becomes invalidated if (say, in the course of an operation) its position is no longer a part of a sequence. An invalidated iterator cannot be dereferenced until it has been reassigned to a valid position. For example:

std::vector<int>::iterator first;
{
    std::vector<int> foo;
    first = foo.begin(); // first is now valid
} // foo falls out of scope and is destroyed
// At this point first is now invalid

The many algorithms and sequence member functions in the C++ standard library have rules governing when iterators are invalidated. Each algorithm is different in the way they treat (and invalidate) iterators.

Navigating with Iterators

As we know, iterators are for navigating sequences. In order to do that an iterator must migrate its position throughout the sequence. Iterators can advance forward in the sequence and some can advance backwards:

auto first = my_vector.begin();
++first;                                             // advance the iterator 1 position
std::advance(first, 1);                              // advance the iterator 1 position
first = std::next(first);                            // returns iterator to the next element
std::advance(first, -1);                             // advance the iterator 1 position backwards
first = std::next(first, 20);                        // returns iterator to the element 20 position forward
first = std::prev(first, 5);                         // returns iterator to the element 5 position backward
auto dist = std::distance(my_vector.begin(), first); // returns distance between two iterators.

For non-random-access iterators, the second argument to std::distance must be reachable from the first by repeated increments. Random-access iterators can also produce a negative distance when the second iterator precedes the first.

Not every iterator supports arithmetic. a = b + 3 works for random-access iterators, but not for forward or bidirectional iterators. std::advance and std::next select an implementation appropriate to the iterator category and are therefore preferable in generic code.

Iterator Concepts

The C++ standard describes several iterator concepts based on how an iterator behaves. They are listed here from least to most capable; each concept adds guarantees to the preceding one:

Algorithms can choose implementations based on the iterator concept they receive. For example, std::distance is constant-time for random-access iterators but advances through the range for other input iterators.

Iterator traits

Iterator traits provide a uniform interface to the properties of iterators. They allow you to retrieve the value, difference, pointer, and reference types, and also the category of the iterator:

template<class Iter>
Iter find(Iter first, Iter last, typename std::iterator_traits<Iter>::value_type val)  {
    while (first != last) {
        if (*first == val)
            return first;
        ++first;
    }
    return last;
}

Category of iterator can be used to specialize algorithms:

template<class BidirIt>
void test(BidirIt a, std::bidirectional_iterator_tag)  {
    std::cout << "Bidirectional iterator is used" << std::endl;
}
 
template<class ForwIt>
void test(ForwIt a, std::forward_iterator_tag)  {
    std::cout << "Forward iterator is used" << std::endl;
}
 
template<class Iter>
void test(Iter a)  {
    test(a, typename std::iterator_traits<Iter>::iterator_category());
}

Iterator categories correspond to these concepts, except that contiguous iterators are not reported through iterator_category. C++20 adds std::contiguous_iterator_tag, but exposes it only through iterator_concept, because changing iterator_category was found to break existing tag dispatch.

std::vector iterator

std::map iterator

Reverse iterators

Stream Iterators

C iterators (pointers)

Write your own generator-backed iterator

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents