Iterator Categories
Explore C++ iterator categories to understand their supported operations such as reading, writing, and navigation. Learn how different iterator types relate to algorithm requirements and performance guarantees to write efficient code.
We'll cover the following...
Supported operations
Now that we have a better understanding of how a range is defined and how we can know when we have reached the end of a sequence, it’s time to look more closely at the operations that iterators can support in order to navigate, read, and write values.
Iterator navigation in a sequence can be done with the following operations:
- Step forward:
std::next(it)or++it - Step backward:
std::prev(it)or--it - Jump to an arbitrary position:
std::advance(it, n)orit += n
Reading and writing a value at the position that the iterator represents is done by dereferencing the iterator. Here is how it looks:
- Read:
auto value = *it - Write:
*it = value
These are the most common operations for iterators that are exposed by containers. But in addition, iterators might operate on data sources where a write or read implies a step forward. Examples of such data sources could be user input, a network connection, or a file. These ...