The iterator library that is part of the C++ Standard Library provides the following helpers for writing generic code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include <iterator> // helpers are defined here template<class Container> void foo(Container& c) { // Generic way to obtain (constant) iterators auto b = std::begin(c); // (1) auto cb = std::cbegin(c); // (2) auto e = std::end(c); // (3) auto ce = std::cend(c); // (4) // Generic way to obtain (constant) reverse iterators auto rb = std::rbegin(c); // (5) auto crb = std::crbegin(c); // (6) auto re = std::rend(c); // (7) auto cre = std::crend(c); // (8) // Generic way to manipulate iterators auto i = std::next(b, 1); // (9) auto d = std::distance(b, i); // (10) auto p = std::prev(i, 1); // (11) std::advance(p, 1); // (12) } |
All the functions above are defined in the <iterator>
header. It’s always preferable to use these generic functions when writing the generic code instead of using equivalent member functions of the containers.
Functions from (1)
to (8)
are defined for built-in arrays and for every type that provides members begin()
and end()
. Note, that std::cbegin()
requires the definition of the constant version of member function c.begin()
.
Functions for (9)
to (12)
: std::prev()
and std::next()
are generic functions to increment or decrement the iterator by the specified number of hops (by default, 1), function std::distance()
is a generic function to calculate the number of hops between the specified pair of iterators and function std::advance()
is a generic equivalent of the operator +=
.
Please note, if either the argument of std::next()
and std::advance()
is negative or the argument of std::prev()
is positive then the specified iterator must be bidirectional iterator (see Categories of Iterators in C++).