01 / 21

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.

C++

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?

Universal Access
One syntax to traverse any container type, from vectors to maps.
Algorithm Ready
STL algorithms like \(\texttt{sort()}\) and \(\texttt{find()}\) require iterators as arguments.
Safe Abstraction
Iterators hide the internal memory layout, reducing bugs from raw pointer math.

The \(\texttt{begin()}\) and \(\texttt{end()}\) Model

10 20 30 40 past end begin() end()
\(\texttt{++it}\) (advance iterator)

The Core Syntax

#include <vector> #include <iostream> int main() { std::vector<int> nums = {10, 20, 30, 40}; // Declare an iterator std::vector<int>::iterator it; for (it = nums.begin(); it != nums.end(); ++it) { std::cout << *it << " "; } // Output: 10 20 30 40 }

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

Random Access Bidirectional Forward Input Output vector, deque, array list, set, map forward_list istream_iterator ostream_iterator More powerful Less

How to Use an Iterator

1
Include the header for the container you need (e.g., <vector>, <set>).
2
Declare the iterator with the container's iterator type, or use auto to let the compiler decide.
3
Initialize with \(\texttt{container.begin()}\) to start at the first element.
4
Loop while the iterator is not equal to \(\texttt{container.end()}\).
5
Dereference with \(*\texttt{it}\) to access the value, then \(\texttt{++it}\) to advance.

Example 1: Traversing a Vector

std::vector<int> scores = {85, 92, 78, 95}; for (auto it = scores.begin(); it != scores.end(); ++it) { std::cout << *it << " "; } // Output: 85 92 78 95

Example 2: Traversing a Set

#include <set> std::set<std::string> colors = {"red", "green", "blue"}; for (auto it = colors.begin(); it != colors.end(); ++it) { std::cout << *it << " "; } // Output (sorted): blue green red

Example 3: Iterating a Map

#include <map> std::map<std::string, int> ages; ages["Alice"] = 17; ages["Bob"] = 16; for (auto it = ages.begin(); it != ages.end(); ++it) { std::cout << it->first // key << ": " << it->second // value << " "; } // Output: Alice: 17 Bob: 16

Read-Only with \(\texttt{const\_iterator}\)

const std::vector<int> data = {1, 2, 3}; // Must use const_iterator for const containers for (auto it = data.cbegin(); it != data.cend(); ++it) { std::cout << *it << " "; // *it = 99; ERROR: can't modify through const_iterator }
\(\texttt{cbegin()}\) / \(\texttt{cend()}\)
Always return a \(\texttt{const\_iterator}\), even on a non-const container.
When to use
Use when you only need to read elements: it prevents accidental modification.

Range-Based For vs Explicit Iterator

// Range-based for (syntactic sugar over iterators) for (auto val : nums) { std::cout << val << " "; } // Equivalent explicit iterator for (auto it = nums.begin(); it != nums.end(); ++it) { std::cout << *it << " "; }

Iterators with STL Algorithms

#include <algorithm> std::vector<int> v = {4, 1, 3, 2}; // Sort the entire container std::sort(v.begin(), v.end()); // v is now {1, 2, 3, 4} // Find an element auto it = std::find(v.begin(), v.end(), 3); if (it != v.end()) { std::cout << "Found: " << *it; }

Common Mistakes

✕ Dereferencing \(\texttt{end()}\)
\(\texttt{end()}\) points past the last element. Writing \(*\texttt{v.end()}\) is undefined behavior and may crash.
✕ Using < instead of !=
Writing \(\texttt{it \lt end()}\) only works for random-access iterators. Use \(\texttt{it != end()}\) for universal compatibility.
✕ Modifying via \(\texttt{const\_iterator}\)
Trying \(*\texttt{it} = 5\) on a const_iterator causes a compile error. Use a regular iterator if you need to write.

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()}\)?