std::ranges::next
来自cppreference.com
                    
                                        
                    
                    
                                                            
                    | 定义于头文件  <iterator> | ||
| 调用签名 | ||
| template< std::input_or_output_iterator I > constexpr I next( I x ); | (1) | (C++20 起) | 
| template< std::input_or_output_iterator I > constexpr I next( I x, 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 x, std::iter_difference_t<I> n, S bound ); | (3) | (C++20 起) | 
返回迭代器 i 的第 n 个后继。
此页面上描述的仿函数实体是 niebloid ,即:
实际上,它们能以函数对象,或以某些特殊编译器扩展实现。
参数
| i | - | 迭代器 | 
| n | - | 要自增的次数 | 
| bound | - | 指代 i所指向的范围结尾的哨位 | 
返回值
1) 迭代器 
i 的后继2) 迭代器 
i 的第 n 个后继3) 迭代器 
i 的第 n 个后继,或首个等于 bound 的迭代器,取决于何者先来到。复杂度
1) 常数
2) 若 
I 实现 std::random_access_iterator 则为常数;否则为线性。3) 若 
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 { 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, std::iter_difference_t<I> n, I 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 <iomanip> #include <iostream> #include <iterator> #include <vector> int main() { std::vector<int> v{ 3, 1, 4 }; { auto n = std::ranges::next(v.begin()); std::cout << *n << '\n'; } { auto n = std::ranges::next(v.begin(), 2); std::cout << *n << '\n'; } { auto n = std::ranges::next(v.begin(), 42, v.end()); std::cout << std::boolalpha; std::cout << (n == v.end()) << '\n'; std::cout << std::noboolalpha; } }
输出:
1 4 true
参阅
| (C++20) | 自减迭代器给定的距离或到边界 (niebloid) | 
| (C++20) | 令迭代器前进给定的距离或到给定的边界 (niebloid) | 
| (C++11) | 令迭代器自增 (函数模板) |