What are iterators in C++?
Answer
Iterators are objects that generalize pointers — they provide a uniform way to traverse elements of any container regardless of the underlying data structure. Algorithms operate on iterators, not containers directly, enabling them to work with any container type. Iterator categories (from weakest to strongest): (1) Input — single pass, read only (std::istream_iterator); (2) Output — single pass, write only (std::ostream_iterator); (3) Forward — multi-pass, read/write (std::forward_list); (4) Bidirectional — forward + backward (std::list, std::set, std::map); (5) Random Access — jump to any position in O(1) (std::vector, std::deque, raw arrays); (6) Contiguous (C++17) — random access + contiguous memory guarantee (std::vector, std::array). Basic usage: std::vector<int> v = {1, 2, 3, 4, 5}; // Iterator-based loop: for (std::vector<int>::iterator it = v.begin(); it != v.end(); ++it) { std::cout << *it << " "; } // Modern auto: for (auto it = v.begin(); it != v.end(); ++it) { *it *= 2; } // Range-based for (preferred when possible): for (auto& x : v) { x *= 2; } // Reverse iteration: for (auto it = v.rbegin(); it != v.rend(); ++it) { std::cout << *it << " "; } // Const iterators (read-only): for (auto it = v.cbegin(); it != v.cend(); ++it) { std::cout << *it; }. Iterator arithmetic (random access only): auto it = v.begin(); it += 3; // Jump to 4th element std::cout << *(it - 1); // 3rd element auto mid = v.begin() + v.size()/2;. std::advance, std::distance, std::next, std::prev: work with any iterator category: std::advance(it, 3); auto dist = std::distance(v.begin(), v.end()); auto next = std::next(it, 2);