How to Use Iterator in C++: Syntax and Examples
In C++, an
iterator is an object that points to elements in a container like vector or list. You use iterators to traverse or modify container elements by incrementing them with ++ and dereferencing with *.Syntax
An iterator is declared using the container's iterator type. You get an iterator to the start of the container with begin() and to the end with end(). Use ++it to move to the next element and *it to access the element.
Container::iterator it = container.begin();— declares an iterator pointing to the first element.it != container.end()— loop condition to stop at the end.++it— moves iterator forward.*it— accesses the element the iterator points to.
cpp
std::vector<int>::iterator it = container.begin(); while(it != container.end()) { // use *it to access element ++it; // move to next }
Example
This example shows how to use an iterator to print all elements of a std::vector.
cpp
#include <iostream> #include <vector> int main() { std::vector<int> numbers = {10, 20, 30, 40, 50}; for(std::vector<int>::iterator it = numbers.begin(); it != numbers.end(); ++it) { std::cout << *it << " "; } std::cout << std::endl; return 0; }
Output
10 20 30 40 50
Common Pitfalls
Common mistakes when using iterators include:
- Dereferencing an iterator that equals
end()causes undefined behavior. - Modifying the container (like adding or removing elements) invalidates existing iterators.
- Using the wrong iterator type (e.g., const_iterator vs iterator) when modifying elements.
cpp
#include <iostream> #include <vector> int main() { std::vector<int> v = {1, 2, 3}; auto it = v.end(); // Wrong: dereferencing end() iterator // std::cout << *it << std::endl; // undefined behavior // Correct way: it = v.begin(); std::cout << *it << std::endl; // prints 1 return 0; }
Output
1
Quick Reference
| Operation | Syntax | Description |
|---|---|---|
| Declare iterator | Container::iterator it; | Creates an iterator for the container |
| Get start | it = container.begin(); | Points to first element |
| Get end | it = container.end(); | Points past last element |
| Access element | *it | Dereferences iterator to get element |
| Move forward | ++it | Moves iterator to next element |
| Move backward (if supported) | --it | Moves iterator to previous element |
| Check end | it != container.end() | Loop until end reached |
Key Takeaways
Use
begin() and end() to get iterators for container traversal.Increment iterators with
++ and access elements with *.Never dereference an iterator equal to
end() as it is invalid.Modifying containers can invalidate iterators, so be careful when changing containers during iteration.
Use the correct iterator type depending on whether you need to modify elements or not.