Can you list the types of iterators and explain their features?
sobes.tech AI
Answer from AI
In C++, there are several types of iterators, which differ in capabilities and supported operations:
-
Input Iterator — allows reading data one element at a time, supports increment and dereference operations. Used for a single pass over data.
-
Output Iterator — allows writing data one element at a time, supports increment and dereference for writing. Used for outputting data.
-
Forward Iterator — combines the capabilities of Input and Output iterators, supports multiple passes over data in one direction.
-
Bidirectional Iterator — extends Forward Iterator, adding the ability to move backwards (decrement).
-
Random Access Iterator — the most powerful type, supports all operations of previous iterators, as well as arbitrary index access, pointer arithmetic, and comparison.
Example of using a random access iterator with a vector:
#include <vector>
#include <iostream>
int main() {
std::vector<int> v = {10, 20, 30, 40};
std::vector<int>::iterator it = v.begin();
std::cout << *it << "\n"; // 10
it += 2;
std::cout << *it << "\n"; // 30
return 0;
}
Each iterator type defines which operations are permissible with it, which is important for choosing the appropriate STL algorithm.