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
EasyLet'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 anInventoryclass that manages a collection of item quantities stored in astd::vector<int>.Your class should provide these methods:
addItem(int quantity)— adds an item quantity to the inventoryprintForward()— uses iterators withbegin()andend()to print all quantities separated by spaces, followed by a newlineprintReverse()— uses reverse iterators withrbegin()andrend()to print all quantities in reverse order, separated by spaces, followed by a newlinedoubleAll()— uses iterators to traverse the vector and double each quantity in placegetTotal()— uses iterators to calculate and return the sum of all quantities
Use the
autokeyword 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
Inventoryand add all four quantities. Then demonstrate iterator usage by:- Printing
Forward:followed by callingprintForward() - Printing
Reverse:followed by callingprintReverse() - Printing
Total: <sum>usinggetTotal() - Calling
doubleAll()to modify the quantities - Printing
After doubling:followed by callingprintForward() - Printing
New total: <sum>usinggetTotal()
- Printing
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: 160This 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 likeit + 3orit1 - 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;
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesC++ Build & CompilationHeader Files & Source FilesNamespaces & ScopeIntroduction to OOP in C++Classes vs ObjectsThe 'this' PointerMethods (Member Functions)Attributes (Data Members)Ctors & Dtors BasicsRecap - Simple Calculator4Class Properties
Instance vs Static MembersGetters and SettersConst Member FunctionsMutable KeywordStatic Methods and VariablesFriend Functions & ClassesRecap - Bank Account Manager7Inheritance
Basic InheritanceInheritance Access LevelsCtor & Dtor Call OrderMethod OverridingVirtual Functions & VTableMultiple InheritanceVirtual InheritanceRecap - Employee Hierarchy2Memory Management
Stack vs Heap MemoryPointers and ReferencesDynamic Memory (new/delete)Smart Pointers in C++RAII in C++Recap - Dynamic Array Manager5Encapsulation
Access Specifiers in C++Access Specifiers In DepthInformation HidingStruct vs ClassNested & Inner ClassesRecap - Student Records System8Polymorphism
Compile vs Runtime PolymorphFunction OverloadingVirtual Functions RevisitedPure Virtual FunctionsAbstract ClassesInterface Design in C++Dynamic Casting & RTTIRecap - Shape Calculator3Constructors & Destructors
Default ConstructorParameterized ConstructorCopy ConstructorMove ConstructorConstructor Init ListsDelegating ConstructorsDestructor Deep DiveRule of Three / Five / ZeroRecap - String Class6Operator Overloading
Intro to Operator OverloadArithmetic Operator OverloadComparison Operator OverloadStream OperatorsAssignment Operator Overload[] and () Operator OverloadType Conversion OperatorsRecap - Matrix Class9Templates
Function TemplatesClass TemplatesTemplate SpecializationVariadic TemplatesSFINAE & Type Traits BasicsRecap - Generic Container