Topic 67 of 83
Iterators
Overview
Iterators are objects that behave like pointers. They traverse STL containers securely and connect containers to algorithms.
Syntax
cpp
std::vector<int> v = {10, 20, 30};
// Standard iterator
std::vector<int>::iterator it;
for (it = v.begin(); it != v.end(); ++it) {
cout << *it; // Dereference to get value
}
// C++11 auto (Much cleaner)
for (auto it = v.begin(); it != v.end(); ++it) {
cout << *it;
}Common Pitfalls
- Erasing an element from a container while iterating through it. This invalidates the iterator and causes crashes. (Correct way: `it = vec.erase(it);`).
Interview Tips
- `v.end()` does NOT point to the last element. It points to one past the last element (out of bounds). This is why loops run while `it != v.end()`.
- Understand Iterator Invalidation: adding elements to a vector might cause it to reallocate memory to a new location, making all your old iterators point to garbage.
Real-World Example
Using iterators with maps.
example
cpp
#include <iostream>
#include <map>
using namespace std;
int main() {
map<int, string> m = {{1, "A"}, {2, "B"}};
// Iterating a map returns std::pair
for (auto it = m.begin(); it != m.end(); ++it) {
cout << "Key: " << it->first << " Val: " << it->second << endl;
}
return 0;
}