liveBook · Manning

Iterator

As explained in 100 C++ Mistakes and How to Avoid Them

An iterator is a C++ library object that provides a uniform means of traversing and accessing elements in a range or container.

An iterator provides a container-oriented way to traverse elements without depending on numeric indexes. It can be compared with a container’s end iterator to determine whether a search succeeded. section 3.1 section 6.8

Mistake: favoring indexes over iterators. Indexing encourages array-shaped solutions, risks off-by-one errors, and excludes containers that cannot be indexed. Iterators keep traversal tied to the container interface. section 6.8

Search with an iterator

std::find returns an iterator. Compare it with values.end() to distinguish a found key from an exhausted search. Modern C++ can limit that iterator to the if statement: if (auto it = std::find(values.begin(), values.end(), key); it != values.end()). section 3.1

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Explains declaration, increment, dereference, end comparison, and container variation, but does not develop iterator internals.
Examples
Demonstrates key lookup with std::find and summation through vector and set iterators.
What it assumes
Assumes basic loops and containers while contrasting familiar array indexing with iterator-based traversal.
What you can do after
Apply it via STL algorithms and container loops to search or process elements while avoiding array-size bookkeeping.
How it connects
Connects iterators with containers, Standard Template Library algorithms, arrays, vectors, sets, and if statements with initializers.

Also explained in

Compare how 15 books explain iterator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.