operator-(std::counted_iterator)
來自 cppreference.com
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 是左運算元,x 是右運算元。
[編輯] 示例
執行此程式碼
#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: operands of operator- do not refer to // elements of the same sequence }
[編輯] 參閱
遞增或遞減 counted_iterator (public member function) | |
(C++20) |
前進迭代器 (function template) |
計算到末尾的帶符號距離 (function template) |