Files
2025-10-25 03:02:53 +03:00

88 lines
2.7 KiB
Markdown

[iterator.operations]
# 24 Iterators library [[iterators]](./#iterators)
## 24.4 Iterator primitives [[iterator.primitives]](iterator.primitives#iterator.operations)
### 24.4.3 Iterator operations [iterator.operations]
[1](#1)
[#](http://github.com/Eelis/draft/tree/9adde4bc1c62ec234483e63ea3b70a59724c745a/source/iterators.tex#L2834)
Since only random access iterators provide+ and- operators, the library provides two
function templatesadvance anddistance[.](#1.sentence-1)
These
function templates
use+ and- for random access iterators (and are, therefore, constant
time for them); for input, forward and bidirectional iterators they use++ to provide linear time
implementations[.](#1.sentence-2)
[🔗](#lib:advance)
`template<class InputIterator, class Distance>
constexpr void advance(InputIterator& i, Distance n);
`
[2](#2)
[#](http://github.com/Eelis/draft/tree/9adde4bc1c62ec234483e63ea3b70a59724c745a/source/iterators.tex#L2863)
*Preconditions*: n is negative only for bidirectional iterators[.](#2.sentence-1)
[3](#3)
[#](http://github.com/Eelis/draft/tree/9adde4bc1c62ec234483e63ea3b70a59724c745a/source/iterators.tex#L2868)
*Effects*: Increments i by n if n is non-negative, and
decrements i by -n otherwise[.](#3.sentence-1)
[🔗](#lib:distance)
`template<class InputIterator>
constexpr typename iterator_traits<InputIterator>::difference_type
distance(InputIterator first, InputIterator last);
`
[4](#4)
[#](http://github.com/Eelis/draft/tree/9adde4bc1c62ec234483e63ea3b70a59724c745a/source/iterators.tex#L2882)
*Preconditions*: last is reachable from first, orInputIterator meets
the *Cpp17RandomAccessIterator* requirements andfirst is reachable from last[.](#4.sentence-1)
[5](#5)
[#](http://github.com/Eelis/draft/tree/9adde4bc1c62ec234483e63ea3b70a59724c745a/source/iterators.tex#L2889)
*Effects*: If InputIterator meets the *Cpp17RandomAccessIterator* requirements,
returns (last - first); otherwise, incrementsfirst until last is reached and returns
the number of increments[.](#5.sentence-1)
[🔗](#lib:next)
`template<class InputIterator>
constexpr InputIterator next(InputIterator x,
typename iterator_traits<InputIterator>::difference_type n = 1);
`
[6](#6)
[#](http://github.com/Eelis/draft/tree/9adde4bc1c62ec234483e63ea3b70a59724c745a/source/iterators.tex#L2905)
*Effects*: Equivalent to: advance(x, n); return x;
[🔗](#lib:prev)
`template<class BidirectionalIterator>
constexpr BidirectionalIterator prev(BidirectionalIterator x,
typename iterator_traits<BidirectionalIterator>::difference_type n = 1);
`
[7](#7)
[#](http://github.com/Eelis/draft/tree/9adde4bc1c62ec234483e63ea3b70a59724c745a/source/iterators.tex#L2918)
*Effects*: Equivalent to: advance(x, -n); return x;