C++ Iterators

πŸ” C++ Iterators

Iterators in C++ act like pointers that allow you to traverse and access elements of STL containers (vector, list, map, set, etc.).
They form the bridge between containers and algorithms.


πŸ”Ή 1. Why Iterators?

  • Traverse containers in a uniform way

  • Work with STL algorithms (sort, find, count, etc.)

  • Abstract container internals

  • Type-safe and flexible


πŸ”Ή 2. Basic Iterator Syntax

container_type::iterator it;

Example:

vector<int>::iterator it;

Modern way:

auto it = v.begin();

πŸ”Ή 3. Common Iterator Functions

FunctionDescription
begin()Points to first element
end()Points after last element
rbegin()Reverse begin
rend()Reverse end

πŸ”Ή 4. Iterating a Container

Vector Example

vector<int> v = {10, 20, 30};

for (auto it = v.begin(); it != v.end(); ++it) {
cout << *it << " ";
}


Reverse Iteration

for (auto it = v.rbegin(); it != v.rend(); ++it) {
cout << *it << " ";
}

πŸ”Ή 5. Iterators with map

map<int, string> m = {{1, "A"}, {2, "B"}};

for (auto it = m.begin(); it != m.end(); ++it) {
cout << it->first << " " << it->second << endl;
}


πŸ”Ή 6. Types of Iterators

1️⃣ Input Iterator

  • Read only

  • One-direction

2️⃣ Output Iterator

  • Write only

3️⃣ Forward Iterator

  • Read & write

  • One-direction

4️⃣ Bidirectional Iterator

  • Forward + backward

  • (list, set, map)

5️⃣ Random Access Iterator

  • Jump to any position

  • (vector, deque, array)


πŸ”Ή 7. const_iterator

Prevents modification of elements.

vector<int>::const_iterator it;

for (it = v.cbegin(); it != v.cend(); ++it) {
cout << *it;
}


πŸ”Ή 8. Iterator Arithmetic

βœ” Only for random-access iterators:

auto it = v.begin();
it += 2; // valid for vector

❌ Invalid for list or set


πŸ”Ή 9. Iterator with Algorithms

#include <algorithm>

auto it = find(v.begin(), v.end(), 20);
if (it != v.end()) {
cout << "Found";
}


πŸ”Ή 10. Invalidated Iterators (Important!)

Some operations invalidate iterators.

vector<int> v = {1, 2, 3};
auto it = v.begin();
v.push_back(4); // it may become invalid

βœ” Safer with list


πŸ”Ή 11. Range-based Loop vs Iterators

for (int x : v) {
cout << x;
}

βœ” Simpler
❌ Less control than iterators


❌ Common Mistakes

auto it = v.end();
cout << *it; // ❌ invalid (end() points past last)

πŸ“Œ Summary

  • Iterators act like pointers

  • Used to traverse STL containers

  • Required for STL algorithms

  • Different containers support different iterator types

  • Be careful with iterator invalidation

You may also like...