operator-(std::counted_iterator)
来自 cppreference.cn
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) |