std::ranges:: next
|
定义于头文件
<iterator>
|
||
|
调用签名
|
||
|
template
<
std::
input_or_output_iterator
I
>
constexpr I next ( I i ) ; |
(1) | (C++20 起) |
|
template
<
std::
input_or_output_iterator
I
>
constexpr I next ( I i, std:: iter_difference_t < I > n ) ; |
(2) | (C++20 起) |
|
template
<
std::
input_or_output_iterator
I,
std::
sentinel_for
<
I
>
S
>
constexpr I next ( I i, S bound ) ; |
(3) | (C++20 起) |
|
template
<
std::
input_or_output_iterator
I,
std::
sentinel_for
<
I
>
S
>
constexpr I next ( I i, std:: iter_difference_t < I > n, S bound ) ; |
(4) | (C++20 起) |
返回迭代器 i 的第 n 个后继。
本页面描述的函数式实体是 算法函数对象 (非正式称为 niebloids ),即:
目录 |
参数
| i | - | 迭代器 |
| n | - | 要向前推进的元素数量 |
| bound | - | 表示 i 所指范围末尾的哨兵值 |
返回值
复杂度
I
与
S
均满足
std::
random_access_iterator
<
I
>
且满足
std::
sized_sentinel_for
<
S, I
>
,或若
I
与
S
满足
std::
assignable_from
<
I
&
, S
>
,则为常数复杂度;否则为线性复杂度。
I
与
S
均满足
std::
random_access_iterator
<
I
>
且
std::
sized_sentinel_for
<
S, I
>
则为常数复杂度;否则为线性复杂度。
可能的实现
struct next_fn { template<std::input_or_output_iterator I> constexpr I operator()(I i) const { ++i; return i; } template<std::input_or_output_iterator I> constexpr I operator()(I i, std::iter_difference_t<I> n) const { ranges::advance(i, n); return i; } template<std::input_or_output_iterator I, std::sentinel_for<I> S> constexpr I operator()(I i, S bound) const { ranges::advance(i, bound); return i; } template<std::input_or_output_iterator I, std::sentinel_for<I> S> constexpr I operator()(I i, std::iter_difference_t<I> n, S bound) const { ranges::advance(i, n, bound); return i; } }; inline constexpr auto next = next_fn(); |
注释
尽管表达式
++
x.
begin
(
)
通常能够编译通过,但这并非绝对保证:
x.
begin
(
)
是一个右值表达式,而标准并未要求对右值进行递增操作必须有效。特别是当迭代器以指针形式实现或其
operator++
具有左值引用限定时,
++
x.
begin
(
)
将无法编译,而
ranges
::
next
(
x.
begin
(
)
)
则可以正常编译。
示例
#include <cassert> #include <iterator> int main() { auto v = {3, 1, 4}; { auto n = std::ranges::next(v.begin()); assert(*n == 1); } { auto n = std::ranges::next(v.begin(), 2); assert(*n == 4); } { auto n = std::ranges::next(v.begin(), v.end()); assert(n == v.end()); } { auto n = std::ranges::next(v.begin(), 42, v.end()); assert(n == v.end()); } }
参见
|
(C++20)
|
将迭代器递减给定距离或至边界
(算法函数对象) |
|
(C++20)
|
将迭代器前进给定距离或至给定边界
(算法函数对象) |
|
(C++11)
|
递增迭代器
(函数模板) |