What Is an Iterator
Swipe to show menu
An iterator is an object that enables traversal of container elements, providing access similar to a generalized pointer. Iterators abstract away the underlying structure of containers and allow you to move through their elements systematically.
In the Standard Template Library (STL), iterators act as an abstraction that separates algorithms from container implementations. Instead of using indices or raw pointers, iterators provide a unified way to access elements across different container types.
This separation allows the same algorithms, like searching, sorting, or copying, to work with containers such as std::vector, std::list, and std::set without changes. By abstracting traversal and access, iterators improve flexibility, encourage code reuse, and simplify maintenance.
main.cpp
12345678910111213141516#include <iostream> #include <vector> int main() { std::vector<int> numbers = {1, 2, 3, 4, 5}; // Declare an iterator for std::vector<int> std::vector<int>::iterator it; // Use the iterator to traverse the vector for (it = numbers.begin(); it != numbers.end(); ++it) std::cout << *it << " "; std::cout << std::endl; }
In this program, you first declare a std::vector<int> named numbers. To traverse the vector, you declare an iterator it of type std::vector<int>::iterator. The iterator is initialized with numbers.begin(), which points to the first element. The loop continues as long as it does not equal numbers.end(), which represents one past the last element. Inside the loop, *it dereferences the iterator to access the value it points to, and ++it advances the iterator to the next element. This pattern allows you to visit each element in the vector in sequence without using indices.
main.cpp
123456789101112131415#include <iostream> #include <list> int main() { std::list<std::string> words = {"hello", "world", "C++", "STL"}; // Declare an iterator for std::list<std::string> std::list<std::string>::iterator it; // Use the iterator to traverse the list for (it = words.begin(); it != words.end(); ++it) std::cout << *it << " "; std::cout << std::endl; }
By using iterators, you can traverse different STL containers in a uniform way. The same loop works for std::vector and std::list, despite their different internal structures. This flexibility enables generic, reusable code that is easier to maintain.
Iterators are the key to making STL algorithms container-agnostic. Any container that provides begin() and end() can be used with STL algorithms, allowing you to apply the same logic across a wide range of data structures.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat