C++ Standard Library<iterator>

In the C++ standard library,<iterator>The header file provides a set of tools for traversing elements in containers. Iterators are one of the core concepts in the C++ Standard Template Library (STL), allowing programmers to access elements in containers in a unified way without needing to worry about the specific implementation details of the container.

An iterator is an object that provides a method for traversing elements in a container. An iterator can be seen as a pointer to an element in a container, but it is more flexible and powerful than a pointer. Iterators can be used to access and modify elements in a container, and can be used together with STL algorithms.

Iterators are mainly divided into the following categories:

  1. Input Iterator: Can only perform single read operations, cannot perform write operations.
  2. Output Iterator: Can only perform single write operations, cannot perform read operations.
  3. Forward Iterator: Can perform read and write operations, and can move forward.
  4. Bidirectional Iterator: In addition to all the operations of a forward iterator, it can also move backward.
  5. Random Access Iterator: In addition to all the operations of a bidirectional iterator, it can also perform random access, such as accessing elements by index.

Common functions (key point)

Function Function Example Description
std::advance(it, n) Move iterator forward by n steps advance(it, 2); Will modify the original iterator
std::distance(a, b) Calculate distance between two iterators distance(v.begin(), v.end()); Returns the number of elements
std::next(it, n) Return a new iterator advanced by n steps auto it2 = next(it, 2); Recommended, does not modify the original value
std::prev(it, n) Return a new iterator moved back by n steps auto it2 = prev(it, 1); Supported since C++11

Iterator adapters (very important)

Iterator adapters can change the behavior of iterators to adapt them to different usage scenarios.

Adapter Function Example
std::back_inserter Tail insertion (calling push_back) back_inserter(vec)
std::front_inserter Head insertion (calling push_front) front_inserter(list)
std::inserter Insert at specified position inserter(vec, it)

Stream iterators (a godsend for simplifying IO)

Type Function Example
std::istream_iterator Read data from input stream istream_iterator<int>(cin)
std::ostream_iterator Write to output stream ostream_iterator<int>(cout, " ")

Iterator syntax

The syntax of iterators is usually as follows:

#include &lt;iterator&gt;

// 使用迭代器遍历容器
for (ContainerType::iterator it = container.begin(); it != container.end(); ++it) {
    // 访问元素 *it
}

Example

Below is an example using<iterator>Header files and iterator traversalstd::vectorexample:

Example

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>

int main() {
    // Create a vector container and initialize it
    std::vector<int> vec = {1, 2, 3, 4, 5};

    // Iterate through the vector using iterators
    for (std::vector<int>::iterator it = vec.begin(); it != vec.end(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;

    // Use the auto keyword to simplify iterator types
    for (auto it = vec.begin(); it != vec.end(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;

    // Use C++11 range-based for loop
    for (int elem : vec) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;

    // Use back_inserter for automatic insertion
    std::vector<int> v2;
    std::fill_n(std::back_inserter(v2), 3, 100);

    // Use ostream_iterator for output
    std::copy(v2.begin(), v2.end(),
              std::ostream_iterator<int>(std::cout, " "));
    std::cout << std::endl;

    return 0;
}

Output:

1 2 3 4 5 
1 2 3 4 5 
1 2 3 4 5 
100 100 100 

Summary

<iterator>The core functions can be summarized into three points:

  • Unified access method: different containers use the same set of traversal logic.
  • Decoupling containers and algorithms: algorithms only depend on iterators.
  • Improved code reusability: the same piece of code can be applied to multiple data structures.

For beginners, it is recommended to prioritize mastering the following:

  • next / prev / distance
  • back_inserter
  • Iterator traversal method
other extensions