TExcelTAD
Home › C++ › C++ Iterators

C++ Iterators

An iterator is an object that points to an element inside a container and knows how to move to the next one. Iterators are the glue of the standard library: every container provides them, and every algorithm works with them. That is why std::sort and std::find work with vectors, deques, arrays and your own types alike.

begin() and end()

Every container has begin(), an iterator to the first element, and end(), an iterator one past the last element. end() does not point to a real element — it marks where to stop. The range [begin, end) is called half-open.

cpp · try it yourself
#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main() {
    vector<string> colors = {"red", "green", "blue"};

    for (vector<string>::iterator it = colors.begin(); it != colors.end(); ++it) {
        cout << *it << " ";
    }
    cout << "\n";

    // the same loop with auto
    for (auto it = colors.begin(); it != colors.end(); ++it) {
        *it += "!";               // modify through the iterator
    }
    cout << colors[0] << " " << colors[2] << "\n";
}
red green blue
red! blue!

Iterators are used like pointers:

Expression Meaning
*it the element the iterator points to
it->member a member of that element
++it move to the next element
--it move to the previous element (bidirectional iterators)
it + n, it[n] jump n positions (random-access iterators only)
it1 == it2 do they point to the same position?

The range-based for loop is just a shorter way of writing the begin/end loop above.

const and reverse iterators

cbegin()/cend() give read-only iterators. rbegin()/rend() walk backwards:

cpp · try it yourself
#include <iostream>
#include <vector>
#include <map>
using namespace std;

int main() {
    vector<int> v = {1, 2, 3, 4, 5};
    for (auto it = v.rbegin(); it != v.rend(); ++it) {
        cout << *it << " ";
    }
    cout << "\n";

    map<string, int> stock = {{"apples", 4}, {"bananas", 0}, {"cherries", 12}};
    for (auto it = stock.cbegin(); it != stock.cend(); ++it) {
        cout << it->first << "=" << it->second << " ";
        // it->second = 1;   // error: const iterator
    }
    cout << "\n";
}
5 4 3 2 1
apples=4 bananas=0 cherries=12

Iterator categories

Not every container can move the same way. Iterators are grouped into categories, and algorithms state which category they need:

Category Can do Example containers
Forward ++ forward_list, unordered_map
Bidirectional ++, -- list, set, map
Random access ++, --, +n, <, [] vector, deque, array
Contiguous (C++20) random access + elements adjacent in memory vector, array, string

That is why std::sort (needs random access) works on a vector but not on a list.

Iterator helpers

The <iterator> header provides functions that work for every category:

cpp · try it yourself
#include <iostream>
#include <list>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;

int main() {
    list<int> l = {10, 20, 30, 40, 50};
    auto it = l.begin();
    advance(it, 3);                                // move forward 3 steps
    cout << *it << "\n";
    cout << distance(l.begin(), it) << "\n";       // how many steps from begin
    cout << *next(l.begin()) << " " << *prev(l.end()) << "\n";

    vector<int> v = {7, 3, 9, 1};
    auto pos = find(v.begin(), v.end(), 9);
    if (pos != v.end()) {
        cout << "9 found at index " << pos - v.begin() << "\n";
    }

    vector<int> copyDest;
    copy(l.begin(), l.end(), back_inserter(copyDest));  // push_back each element
    cout << copyDest.size() << " elements copied\n";
}
40
3
20 50
9 found at index 2
5 elements copied

Iterator invalidation

Changing a container can make existing iterators invalid — using them afterwards is undefined behaviour. The rules differ per container:

Container Invalidated by
vector insertion that reallocates (all), insert/erase (everything after the position)
deque insertion anywhere (all iterators), erase in the middle
list, set, map only iterators to erased elements

The safe pattern for erasing while iterating is to use the iterator that erase returns:

cpp · try it yourself
#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8};
    for (auto it = v.begin(); it != v.end(); ) {
        if (*it % 3 == 0) {
            it = v.erase(it);    // erase returns the next valid iterator
        } else {
            ++it;
        }
    }
    for (int x : v) cout << x << " ";
    cout << "\n";
}
1 2 4 5 7 8

Tip: C++20 offers an even simpler way: std::erase_if(v, [](int x) { return x % 3 == 0; }); does the whole loop above in one line, for all standard containers.

Test yourself

What does end() point to?

  1. The last element
  2. One past the last element
  3. The first element
  4. nullptr

Which iterator category does std::list provide?

  1. Forward
  2. Bidirectional
  3. Random access
  4. Contiguous

How do you safely erase elements from a vector while iterating?

  1. Call erase(it) then ++it
  2. Assign it = v.erase(it) and only ++it otherwise
  3. Use a range-based for loop
  4. You cannot erase while iterating