CKTIS / C++
std::next — an advanced copy of an iterator
std::next from <iterator> returns a copy of an iterator advanced by n positions, defaulting to one. It also supports iterators without operator +. It does not check range boundaries; a negative offset requires a bidirectional iterator.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <iterator>
template<class InputIterator>
constexpr InputIterator next(
InputIterator x,
typename std::iterator_traits<InputIterator>::difference_type n = 1
);std::next(x, n) takes an iterator by value, performs the equivalent of std::advance(x, n), and returns the result. Omitting n means 1. Unlike std::advance, it does not assign the new position to the supplied iterator variable.
It works with input iterators meeting the Cpp17InputIterator requirements. Negative n requires a bidirectional iterator. The cost is O(1) for random-access iterators and O(|n|) otherwise. For example, a std::list iterator does not support +, but you can advance it with std::next.
The function receives no range boundary and does not check one. You must not move the iterator beyond its permitted positions. The result may equal end(), but must not then be dereferenced. Copying a single-pass input iterator does not guarantee independent reading: advancing the copy can consume shared input and invalidate earlier copies.
Do not confuse std::next with std::ranges::next: the latter also provides sentinel overloads, including std::ranges::next(x, n, bound), which stops advancing at the boundary. The example below uses bidirectional iterators: first stays at 10, third points to 30, and stepping backward from end() gives 40.
Examples
#include <iostream>
#include <iterator>
#include <list>
int main() {
const std::list<int> values{10, 20, 30, 40};
auto first = values.begin();
auto third = std::next(first, 2);
auto last = std::next(values.end(), -1);
std::cout << *first << ' ' << *third << ' ' << *last << '\n';
}
Result
10 30 40
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.