Iterators in C++
Lesson Introduction
Welcome to the world of iterators in C++! Iterators are fundamental to the C++ Standard Library, enabling efficient traversal and manipulation of container elements. The goal of this lesson is to help you understand what iterators are, how to use them effectively, and why they are essential.
By the end of this lesson, you'll know how to declare and use iterators to traverse and modify elements in a std::vector.
Basic Concept of Iterators and Types of Iterators
So, what exactly is an iterator? An iterator is an object that lets you access elements in a container (such as std::vector, std::list, etc.) sequentially without exposing the container's underlying representation.
There are several types of iterators in C++:
- Input Iterators: Read-only access to elements.
- Output Iterators: Write-only access to elements.
- Forward Iterators: Read and write access, single-pass.
- Bidirectional Iterators: Read and write access, and can move both forward and backward.
- Random-Access Iterators: Read and write access, and can move to any element in constant time.
For this lesson, we will focus on Random-Access Iterators, typically used with std::vector.
Traversing Elements Using an Iterator
To iterate over the elements of a vector, we use the begin() and end() member functions:
- begin(): Returns an iterator to the first element of the container.
- end(): Returns an iterator to just past the last element of the container.
An iterator can be incremented, decremented, and dereferenced. Let's break this down:
- Increment: Moves the iterator to the next element.
- Decrement: Moves the iterator to the previous element.
- Dereference: Accesses the value the iterator points to.
Remember, the dereference operator (*) is used to obtain the value that the iterator points to, much like how you dereference pointers.
In this snippet, we initialize it to the beginning of the vector and increment it to access the second element. Note that:
- the iterator has type
<data type>::iterator - we dereference the iterator with
*, like a pointer.
