Iterator (C++)

An iterator is an object that points to an element in a container and lets you move through the container one element at a time. It works like a generalized pointer.

C++

Most STL containers provide .begin() (pointing to the first element) and .end() (pointing just past the last). You advance an iterator with ++ and read the current element by dereferencing it with *.

Iterators are what let generic algorithms like std::sort and std::find work on any container, since they all expose the same iterator interface.

Syntax

for (auto it = c.begin(); it != c.end(); ++it) { *it; }

Examples

C++

#include <iostream>
#include <vector>

int main() {
    std::vector<int> nums = {10, 20, 30};
    for (auto it = nums.begin(); it != nums.end(); ++it) {
        std::cout << *it << std::endl;
    }
    return 0;
}

Output:

10
20
30

Learn it in a lesson

See also

Back to the Dictionary