Previous chapter: Chapter 15: Standard Template Library (STL): Containers in C++
While containers (Chapter 15) store data, Iterators and Algorithms are the mechanisms that make the STL truly powerful, allowing you to manipulate the data stored in those containers efficiently and uniformly.
1. Iterators: The General Pointer
An iterator is a concept in C++ that acts like a generic pointer. It abstracts the method of accessing elements in a container, allowing algorithms to work on any container type (vector, list, map, etc.) without knowing the container's internal structure.
Key Iterator Functions
Every STL container provides methods to get iterators:
| Function | Description |
|---|---|
| .begin() | Returns an iterator pointing to the first element. |
| .end() | Returns an iterator pointing to one position past the last element. |
Using Iterators to Traverse
Iterators are manipulated using standard pointer operators: * (dereference) and ++ (move to the next element).
#include <vector>
std::vector<int> data = {1, 2, 3, 4};
// Iterate and print using an iterator
for (auto it = data.begin(); it != data.end(); ++it) {
std::cout << *it << " "; // Dereference to get the value
}
// Output: 1 2 3 4
2. STL Algorithms
Algorithms are generic functions (defined in the <algorithm> header) that perform common operations on ranges of elements, defined by a pair of iterators (a beginning and an end).
Join the conversation! Your thoughts help the community grow.