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!
begin() and end() MethodsAlmost all STL containers have two crucial methods that return iterators:
.begin() - Returns an iterator pointing to the very first element..end() - Returns an iterator pointing to the memory space located just after the last element. (It acts as an stopping point indicator).#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; }
autoWriting 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.
// 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!
What does the `.end()` function return an iterator to?