operator-(std::counted_iterator)
出自cppreference.com
< cpp | iterator | counted iterator
template< std::common_with<I> I2 > friend constexpr std::iter_difference_t<I2> operator-( |
(C++20 起) | |
計算兩個迭代器適配器間的距離。
若 x 與 y 不指向同一序列的元素則行為未定義。即必須存在某個 n 使得 std::next(x.base(), x.count() + n) 與 std::next(y.base(), y.count() + n) 指代同一元素。
此函數模板對常規的無限定或有限定查找不可見,而只能在 std::counted_iterator<I> 為實參的關聯類時由實參依賴查找找到。
目錄 |
[編輯] 參數
x, y | - | 要計算差的迭代器適配器 |
[編輯] 返回值
y.count() - x.count()
[編輯] 註解
由於長度向下計數,而非向上,operator- 的實參在底層表達式中的順序是逆轉的,即 y 為 lhs 而 x 為 rhs。
[編輯] 示例
運行此代碼
#include <initializer_list> #include <iterator> int main() { static constexpr auto v = {1, 2, 3, 4, 5, 6}; constexpr std::counted_iterator<std::initializer_list<int>::iterator> it1{v.begin(), 5}, it2{it1 + 3}, it3{v.begin(), 2}; static_assert(it1 - it2 == -3); static_assert(it2 - it1 == +3); // static_assert(it1 - it3 == -3); // UB:operator- 的操作数不指代同一序列的元素 }
[編輯] 參閱
推進或回退 counted_iterator (公開成員函數) | |
(C++20) |
令迭代器前進 (函數模板) |
計算到末尾的有符號距離 (函數模板) |