Sobes.tech
Junior — Middle

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:

  1. Input Iterator — allows reading data one element at a time, supports increment and dereference operations. Used for a single pass over data.

  2. Output Iterator — allows writing data one element at a time, supports increment and dereference for writing. Used for outputting data.

  3. Forward Iterator — combines the capabilities of Input and Output iterators, supports multiple passes over data in one direction.

  4. Bidirectional Iterator — extends Forward Iterator, adding the ability to move backwards (decrement).

  5. 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.