Using Iterators
in C++
Learn how to traverse containers using iterators with \(\texttt{begin()}\) and \(\texttt{end()}\): the universal way to walk through data in the Standard Library.
What Is an Iterator?
An iterator is an object that acts like a pointer to an element inside a container. It lets you step through every element one at a time, without needing to know how the container is stored in memory.
Iterators work with every standard container: vector, list, set, map, and more.
Why Do Iterators Matter?
The \(\texttt{begin()}\) and \(\texttt{end()}\) Model
The Core Syntax
Iterator vs Index Access
| Iterator Loop | Index Loop | |
|---|---|---|
| Syntax | \(\texttt{for(it=begin(); it!=end(); ++it)}\) | \(\texttt{for(i=0; i < size(); ++i)}\) |
| Works with vector | ✓ | ✓ |
| Works with list | ✓ | ✕ |
| Works with set/map | ✓ | ✕ |
| STL algorithm compatible | ✓ | ✕ |
Iterator Categories
How to Use an Iterator
Example 1: Traversing a Vector
Example 2: Traversing a Set
Example 3: Iterating a Map
Read-Only with \(\texttt{const\_iterator}\)
Range-Based For vs Explicit Iterator
Iterators with STL Algorithms
Common Mistakes
Iterator Cheat Sheet
| Operation | Syntax | Meaning |
|---|---|---|
| Start | \(\texttt{c.begin()}\) | Iterator to first element |
| End sentinel | \(\texttt{c.end()}\) | Past-the-end (not valid to read) |
| Read value | \(*\texttt{it}\) | Dereference the iterator |
| Advance | \(\texttt{++it}\) | Move to next element |
| Compare | \(\texttt{it != c.end()}\) | Check if there are more elements |
| Const read | \(\texttt{c.cbegin()}\) / \(\texttt{c.cend()}\) | Read-only iterator |
Question 1 of 5
What does \(\texttt{end()}\) point to in a C++ container?
Question 2 of 5
Which operator is used to access the value an iterator points to?
Question 3 of 5
Which comparison should you use in a loop condition for maximum compatibility across all container types?
Question 4 of 5
When iterating over a \(\texttt{std::map}\), how do you access the key of the current element?
Question 5 of 5
What is the advantage of using \(\texttt{cbegin()}\) and \(\texttt{cend()}\) instead of \(\texttt{begin()}\) and \(\texttt{end()}\)?