Welcome back to CodeYourCraft! Today, we're diving into the fascinating world of C++ Random Access Iterators. Let's get started!
Random Access Iterators, often abbreviated as RAIs, are a type of iterators in C++ that allow us to access any element of a container directly by using its index. They are named so because we can access any element "randomly" by its position.
RAIs are incredibly useful as they provide a uniform interface to traverse and manipulate containers. This means we can write code that works with all kinds of containers, like arrays, vectors, lists, etc., without worrying about their specific implementation details.
A Random Access Iterator supports four operations:
dereference operator*: Provides access to the element the iterator points to.increment operator++: Moves the iterator to the next element.decrement operator--: Moves the iterator to the previous element.subscript operator[]: Allows us to access the element directly using its index.Let's create a simple IntArray class and implement a Random Access Iterator for it.
#include <iostream>
#include <vector>
class IntArray {
public:
// ...
class iterator {
public:
iterator(std::vector<int>::iterator it) : iter_(it) {}
int operator*() const { return *iter_; }
iterator& operator++() { ++iter_; return *this; }
iterator operator++(int) { iterator temp(*this); ++(*this); return temp; }
iterator& operator--() { --iter_; return *this; }
iterator operator--(int) { iterator temp(*this); --(*this); return temp; }
bool operator==(const iterator& other) const { return iter_ == other.iter_; }
bool operator!=(const iterator& other) const { return iter_ != other.iter_; }
private:
std::vector<int>::iterator iter_;
};
iterator begin() { return iterator(data_.begin()); }
iterator end() { return iterator(data_.end()); }
private:
std::vector<int> data_;
};
int main() {
IntArray arr = {1, 2, 3, 4, 5};
IntArray::iterator it = arr.begin();
std::cout << *(it + 2) << std::endl; // prints 3
return 0;
}What does a Random Access Iterator support?
Stay tuned for more! In the next lesson, we'll explore how to implement Bidirectional Iterators in C++. See you then! šÆ