Menu
Coddy logo textTech

Iterators

Part of the Object Oriented Programming section of Coddy's C++ journey — lesson 72 of 104.

Iterators are objects that act as a bridge between containers and algorithms. They provide a uniform way to access elements in any container, regardless of how that container stores its data internally. Think of an iterator as a generalized pointer that knows how to move through a container.

Every STL container provides begin() and end() methods. The begin() iterator points to the first element, while end() points to one past the last element - a sentinel that marks where to stop:

#include <vector>
#include <iostream>

int main() {
    std::vector<int> nums = {10, 20, 30};
    
    for (std::vector<int>::iterator it = nums.begin(); it != nums.end(); ++it) {
        std::cout << *it << " ";  // Dereference to get value
    }
    // Output: 10 20 30
}

The auto keyword simplifies iterator declarations significantly:

for (auto it = nums.begin(); it != nums.end(); ++it) {
    *it *= 2;  // Modify elements through iterator
}
// nums is now {20, 40, 60}

Iterators come in different categories based on their capabilities. Random access iterators (like those from vector) support arithmetic operations such as it + 3 or it1 - it2.

Bidirectional iterators (from list, map) can move forward and backward with ++ and --. Forward iterators can only move in one direction.

For reverse traversal, use rbegin() and rend():

for (auto rit = nums.rbegin(); rit != nums.rend(); ++rit) {
    std::cout << *rit << " ";  // Prints in reverse order
}
challenge icon

Challenge

Easy

Let's build an inventory tracking system that uses iterators to traverse and manipulate collections of items. You'll practice using different iterator types to navigate through data in various ways.

You'll organize your code across two files:

  • Inventory.h: Define an Inventory class that manages a collection of item quantities stored in a std::vector<int>.

    Your class should provide these methods:

    • addItem(int quantity) — adds an item quantity to the inventory
    • printForward() — uses iterators with begin() and end() to print all quantities separated by spaces, followed by a newline
    • printReverse() — uses reverse iterators with rbegin() and rend() to print all quantities in reverse order, separated by spaces, followed by a newline
    • doubleAll() — uses iterators to traverse the vector and double each quantity in place
    • getTotal() — uses iterators to calculate and return the sum of all quantities

    Use the auto keyword for your iterator declarations to keep the code clean.

  • main.cpp: Read four integer inputs (each on a separate line) representing item quantities.

    Create an Inventory and add all four quantities. Then demonstrate iterator usage by:

    1. Printing Forward: followed by calling printForward()
    2. Printing Reverse: followed by calling printReverse()
    3. Printing Total: <sum> using getTotal()
    4. Calling doubleAll() to modify the quantities
    5. Printing After doubling: followed by calling printForward()
    6. Printing New total: <sum> using getTotal()

For example, with inputs 10, 25, 15, and 30:

Forward: 10 25 15 30 
Reverse: 30 15 25 10 
Total: 80
After doubling: 20 50 30 60 
New total: 160

This challenge lets you practice both reading elements through iterators (for printing and summing) and modifying elements through iterators (for doubling). You'll also see how reverse iterators make backward traversal straightforward without any index manipulation.

Cheat sheet

Iterators are objects that provide a uniform way to access elements in containers. They act as generalized pointers that know how to move through a container.

Every STL container provides begin() and end() methods. The begin() iterator points to the first element, while end() points to one past the last element:

std::vector<int> nums = {10, 20, 30};

for (std::vector<int>::iterator it = nums.begin(); it != nums.end(); ++it) {
    std::cout << *it << " ";  // Dereference to get value
}

Use the auto keyword to simplify iterator declarations:

for (auto it = nums.begin(); it != nums.end(); ++it) {
    *it *= 2;  // Modify elements through iterator
}

Iterator categories based on capabilities:

  • Random access iterators (e.g., vector) support arithmetic operations like it + 3 or it1 - it2
  • Bidirectional iterators (e.g., list, map) can move forward and backward with ++ and --
  • Forward iterators can only move in one direction

For reverse traversal, use rbegin() and rend():

for (auto rit = nums.rbegin(); rit != nums.rend(); ++rit) {
    std::cout << *rit << " ";  // Prints in reverse order
}

Try it yourself

#include <iostream>
#include "Inventory.h"

using namespace std;

int main() {
    // Read four integer inputs
    int q1, q2, q3, q4;
    cin >> q1;
    cin >> q2;
    cin >> q3;
    cin >> q4;

    // TODO: Create an Inventory object

    // TODO: Add all four quantities to the inventory

    // TODO: Print "Forward: " then call printForward()

    // TODO: Print "Reverse: " then call printReverse()

    // TODO: Print "Total: " followed by the result of getTotal()

    // TODO: Call doubleAll() to modify the quantities

    // TODO: Print "After doubling: " then call printForward()

    // TODO: Print "New total: " followed by the result of getTotal()

    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming