How do I understand iterator categories and sentinel?

Iterators are a fundamental part of the C++ Standard Library, enabling traversal of containers without exposing the details of their implementation. Understanding iterator categories and sentinels is crucial for effective use of STL (Standard Template Library) algorithms.

Iterator Categories

Iterator categories define the capabilities of an iterator. There are several categories:

  • Input Iterator: Can be read-only, allows traversing elements once.
  • Output Iterator: Can be written-only, allows writing elements once.
  • Forward Iterator: Can be read and written, allows multiple passes over a range.
  • Bidirectional Iterator: Like forward iterators, but can also be traversed backwards.
  • Random Access Iterator: Supports arbitrary jumps, allowing for quick access to elements.

Sentinels

A sentinel is a special value used to represent the end of a range. It helps avoid the need for separate size information when iterating over a collection. In C++, a common example of a sentinel would be the end iterator of a container.

Example of Iterators and Sentinels


#include <iostream>
#include <vector>

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};

    // Using an iterator to traverse the vector
    for (auto it = vec.begin(); it != vec.end(); ++it) {
        std::cout << *it << " ";
    }
    return 0;
}
    

C++ iterators iterator categories STL C++ Standard Library sentinels input iterator output iterator forward iterator bidirectional iterator random access iterator