operator-(std::counted_iterator)
来自 cppreference.cn
< 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: operands of operator- do not refer to // elements of the same sequence }
[编辑] 参见
递增或递减 counted_iterator (公共成员函数) | |
(C++20) |
递增迭代器 (函数模板) |
计算到末尾的有符号距离 (函数模板) |