operator-(std::common_iterator) - cppreference.com
Namespaces
Variants

operator-(std::common_iterator)

From cppreference.com
 
 
Iterator library
Iterator concepts
Iterator primitives
Algorithm concepts and utilities
Indirect callable concepts
Common algorithm requirements
(C++20)
(C++20)
(C++20)
Utilities
(C++20)
Iterator adaptors
Range access
(C++11)(C++14)
(C++14)(C++14)  
(C++11)(C++14)
(C++14)(C++14)  
(C++17)(C++20)
(C++17)
(C++17)
 
 
template< std::sized_sentinel_for<I> I2, std::sized_sentinel_for<I> S2 >
    requires std::sized_sentinel_for<S, I2>
friend constexpr std::iter_difference_t<I2>
    operator-( const common_iterator& x, const std::common_iterator<I2, S2>& y );
(since C++20)

Computes the distance between the iterators and/or sentinels held by underlying std::variant member objects var . Two sentinels are considered equal.

Let Ix be x.var.index() and Iy be y.var.index():

  • If Ix == 1 && Iy == 1 (i.e. both x and y hold sentinels), the distance is 0.
  • Otherwise, the distance is std::get<Ix>(x.var) - std::get<Iy>(y.var).


If x.var.valueless_by_exception() || y.var.valueless_by_exception() is true, the behavior is undefined.

(until C++26)

If x.var.valueless_by_exception() || y.var.valueless_by_exception() is true:

(since C++26)

This function template is not visible to ordinary unqualified or qualified lookup, and can only be found by argument-dependent lookup when std::common_iterator<I> is an associated class of the arguments.

Parameters

x, y - iterator adaptors to compute the difference of

Return value

The distance between the underlying iterators and/or sentinels, as described above.

Example

#include <algorithm>
#include <iostream>
#include <iterator>

int main()
{
    int a[]{0, 1, 2, 3, 4, 5};
    
    using CI = std::common_iterator<std::counted_iterator<int*>,
                                    std::default_sentinel_t>;
    
    CI i1{std::counted_iterator{a + 1, 2}};
    CI i2{std::counted_iterator{a, 3}};
    CI s1{std::default_sentinel};
    CI s2{std::default_sentinel};
    
    std::cout << (s2 - s1) << ' '
              << (i2 - i1) << ' '
              << (i1 - s1) << '\n';
}

Output:

0 -1 -2

Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
LWG 3574 C++20 variant was fully constexpr (P2231R1) but common_iterator was not also made constexpr

See also