What is Iterator in C++: Simple Explanation and Example
iterator is an object that points to elements inside a container like a vector or list and allows you to access or move through these elements one by one. It works like a bookmark or a pointer that helps you navigate through a collection without exposing its internal structure.How It Works
Think of an iterator as a bookmark inside a book. Instead of flipping pages randomly, the bookmark shows you exactly where you are. In C++, containers like vectors or lists hold many elements, and an iterator points to one element at a time.
You can move the iterator forward or backward to visit each element in order. This way, you can read or change elements without worrying about how the container stores them internally. The iterator hides the details and gives you a simple way to walk through the collection.
Example
This example shows how to use an iterator to print all elements in a std::vector of integers.
#include <iostream> #include <vector> int main() { std::vector<int> numbers = {10, 20, 30, 40, 50}; // Create an iterator pointing to the first element std::vector<int>::iterator it = numbers.begin(); // Loop until the iterator reaches the end while (it != numbers.end()) { std::cout << *it << " "; // Access the element ++it; // Move to the next element } std::cout << std::endl; return 0; }
When to Use
Use iterators when you want to access or modify elements in a container one by one without knowing how the container stores them. They are especially useful for generic programming, where your code works with different container types like vectors, lists, or sets.
For example, if you want to loop through a list of users, process data in a vector, or copy elements from one container to another, iterators provide a clean and consistent way to do this. They also help avoid errors by controlling how you move through the container safely.
Key Points
- An iterator acts like a pointer to elements inside a container.
- It allows sequential access without exposing container details.
- You can move iterators forward (and sometimes backward) to traverse elements.
- Iterators enable writing flexible code that works with many container types.