std::ranges::next
來自 cppreference.com
< cpp | 迭代器 (iterator)
定義於標頭檔案 <iterator> |
||
呼叫簽名 (Call signature) |
||
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 所指向的範圍末尾的哨兵 |
[編輯] 返回值
1) 迭代器 i 的後繼。
2) 迭代器 i 的第 n 個後繼。
3) 第一個等同於 bound 的迭代器。
4) 迭代器 i 的第 n 個後繼,或第一個等同於 bound 的迭代器,以先遇到者為準。
[編輯] 複雜度
1) 常數。
3) 如果
I
和 S
都滿足 std::random_access_iterator<I> 和 std::sized_sentinel_for<S, I>,或者如果 I
和 S
都滿足 std::assignable_from<I&, S>,則為常數時間;否則為線性時間。[編輯] 可能的實現
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) |
遞增迭代器 (函式模板) |