C++ Iterators

C++ Iterators: Traversing Containers

An Iterator is an object that acts like a pointer. It points to a memory address of an element inside an STL container (like a vector, list, set, or map).

Iterators are the magic "bridge" that allows algorithms to manipulate data inside containers regardless of what type of container it is!


1. The begin() and end() Methods

Almost all STL containers have two crucial methods that return iterators:

Iterator Example

#include <iostream>
#include <vector>
using namespace std;

int main() { vector<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};

// Declaring an iterator for a string vector vector<string>::iterator it;

// Using a traditional loop with iterators for (it = cars.begin(); it != cars.end(); ++it) { // Dereference the iterator (*) to get the actual value cout << *it << "\n"; }

return 0; }


2. The Power of auto

Writing vector<string>::iterator can be very long and tedious to type out. Modern C++ (C++11 and newer) introduced the auto keyword, which lets the compiler automatically determine the correct data type.

Auto Keyword Example

// The compiler sees cars.begin() and automatically makes 'it' an iterator!
for (auto it = cars.begin(); it != cars.end(); ++it) {
  cout << *it << "\n";
}

Pro Tip: This is exactly what the modern "range-based for loop" does under the hood!


Exercise

?

What does the `.end()` function return an iterator to?