Hi! On Tue, Jul 14, 2026 at 12:30 PM Patrick Palka <[email protected]> wrote: > > For segmented iterators, ranges::distance is equivalent to the sum of > ranges::distance of each of its segments. > > PR libstdc++/123211 > > libstdc++-v3/ChangeLog: > > * include/bits/ranges_base.h (__distance_fn::operator()): For > the non-sized-sentinel overload, > --- > libstdc++-v3/include/bits/ranges_base.h | 10 ++++++++++ > 1 file changed, 10 insertions(+) > > diff --git a/libstdc++-v3/include/bits/ranges_base.h > b/libstdc++-v3/include/bits/ranges_base.h > index ce1c40fc17f6..7f169feaa6b1 100644 > --- a/libstdc++-v3/include/bits/ranges_base.h > +++ b/libstdc++-v3/include/bits/ranges_base.h > @@ -994,6 +994,16 @@ namespace ranges > constexpr iter_difference_t<_It> > operator()[[nodiscard]](_It __first, _Sent __last) const > { > + if constexpr (__segmented_iterator<_It> && same_as<_It, _Sent>) > + { > + iter_difference_t<_It> __n = 0; > + std::__for_each_segment(__first, __last, [this, &__n](auto > __first, auto __last) { > + __n += iter_difference_t<_It>(this->operator()(__first, > __last)); > + return __last; > + }); > + return __n; > + } > + > iter_difference_t<_It> __n = 0; > while (__first != __last) > { > -- > 2.55.0.141.g55526a1826 >
Great to see this optimization into libstdc++! Beyond ranges::distance, I think there are more algorithms we can optimize for segmented iterators. I helped implement some of these for libc++, and I'd love to contribute similar optimizations to libstdc++ too!
