🚶♂️ C++ Iterator – Move Through Containers Like a Pro
An iterator in C++ is like a smart pointer that walks through elements of a container (like a vector or list) one by one.
It helps you loop over containers without knowing their structure. Imagine a robot with a map who knows where to go next!
📦 Why Use Iterators?
- They work with all STL containers (like
vector
,list
, etc.) - They are more flexible than plain loops
- You can move them forward, backward, and even modify data
🔧 Example: Iterating Over a Vector
#include <iostream> #include <vector> using namespace std; int main() { vector<int> nums = {10, 20, 30}; vector<int>::iterator it; for (it = nums.begin(); it != nums.end(); ++it) { cout << *it << " "; } return 0; }
🎯 Shortcut with auto Keyword
C++11 introduced auto
to make code shorter and easier to read.
#include <iostream> #include <vector> using namespace std; int main() { vector<int> nums = {5, 10, 15}; for (auto it = nums.begin(); it != nums.end(); ++it) { cout << *it << " "; } return 0; }
💡 Tip: Common Iterator Functions
begin()
– points to the first elementend()
– points just after the last element*it
– gives you the value at iterator++it
– moves to the next item
✅ Summary
- Iterators help you loop through containers easily
- Use
begin()
andend()
to define your loop auto
makes the code clean and readable