Useful Functions

C++ offers several tools to make the iteration process simpler yet safer.

The global functions std::begin, std::end, std::prev, std::next, std::distance and std::advance make your handling of the iterators a lot easier. Only the function std::prev requires a bidirectional iterator. All functions need the header <iterator>. The table gives you an overview:

Global function Description
std::begin(cont) Returns a begin iterator to the container cont.
std::end(cont) Returns an end iterator to the container cont.
std::rbegin(cont) Returns a reverse begin iterator to the container cont.
std::rend(cont) Returns a reverse end iterator to the container cont.
std::cbegin(cont) Returns a constant begin iterator to the container cont.
std::cend(cont) Returns a constant end iterator to the container cont.
std::crbegin(cont) Returns a reverse constant begin iterator to the container cont.
std::crend(cont) Returns a reverse constant end iterator to the container cont.
std::prev(it) Returns an iterator, which points to a position before it
std::next(it) Returns an iterator, which points to a position after it.
std::distance(fir, sec) Returns the number of elements between fir and sec.
std::advance(it, n) Puts the iterator it n positions further.

Useful functions for iterators

Now, the application of the useful functions.

Get hands-on with 1200+ tech skills courses.