Iterators are the architectural bridge that decouples STL containers from STL algorithms. An iterator acts as an generalized smart pointer that traverses through the elements of any container uniformly.
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums = {10, 20, 30, 40, 50};
// Forward iteration
std::cout << "Forward: ";
for (auto it = nums.begin(); it != nums.end(); ++it) {
std::cout << *it << " ";
}
std::cout << "\n";
// Reverse iteration
std::cout << "Reverse: ";
for (auto rit = nums.rbegin(); rit != nums.rend(); ++rit) {
std::cout << *rit << " ";
}
std::cout << "\n";
return 0;
}
Boost your C++ proficiency by studying these closely connected core modules:
Using iterators as inputs to sort and transform algorithms.
Random access iterators inside dynamic arrays.
Bidirectional iterators in linked lists.