Junior — Middle
Explain the purpose and main characteristics of an object of type random_access_iterator.
sobes.tech AI
Answer from AI
A random_access_iterator is a type of iterator in C++ that supports arbitrary access to container elements with constant time access. It allows not only sequential movement through elements but also jumping to an arbitrary number of positions forward or backward, using arithmetic operations and comparisons.
Main features:
- Support for operations: ++, --, +, -, +=, -=
- Access to element by index via operator []
- Ability to compare iterators (<, <=, >, >=)
Example usage with a vector:
#include <vector>
#include <iostream>
int main() {
std::vector<int> v = {10, 20, 30, 40, 50};
auto it = v.begin();
it += 3; // move to the 4th element
std::cout << *it << std::endl; // will output 40
std::cout << it[1] << std::endl; // access to the next element, will output 50
}
random_access_iterator is typically implemented in containers such as std::vector, std::deque, and arrays.