[libcxx-commits] [libcxx] [libc++] Implement `ranges::fold_right` (PR #193997)

Connector Switch via libcxx-commits libcxx-commits at lists.llvm.org
Thu Apr 30 22:44:31 PDT 2026


================
@@ -23,6 +23,7 @@
 #include <__iterator/concepts.h>
 #include <__iterator/iterator_traits.h>
 #include <__iterator/next.h>
+#include <__iterator/reverse_iterator.h>
----------------
c8ef wrote:

```cpp
template <class _InputIterator, class _Sent, class _Func, class _Proj>
_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 _InputIterator
__for_each_backward(_InputIterator __first, _Sent __last, _Func&& __func, _Proj& __proj) {
#ifndef _LIBCPP_CXX03_LANG
  if constexpr (is_same<_InputIterator, _Sent>::value && __is_segmented_iterator_v<_InputIterator>) {
    using __local_iterator_t = typename __segmented_iterator_traits<_InputIterator>::__local_iterator;
    std::__for_each_segment_backward(__first, __last, [&](__local_iterator_t __lfirst, __local_iterator_t __llast) {
      std::__for_each_backward(__lfirst, __llast, __func, __proj);
    });
    return __last;
  }
#endif
  --__last;
  for (; __first != __last; --__last)
    std::__invoke(__func, std::__invoke(__proj, *__last));
  std::__invoke(__func, std::__invoke(__proj, *__last));
  return __last;
}
```

I think we could introduce `__for_each_backward` like above, but it lacks the elegance of forward iteration. Using reverse iterators feels more natural, and we already have precedents for this approach. WDYT?

https://github.com/llvm/llvm-project/blob/a7a2dc59616a8cb1198d933bcdf55ebdbd78894c/libcxx/include/__algorithm/radix_sort.h#L198-L211

https://github.com/llvm/llvm-project/pull/193997


More information about the libcxx-commits mailing list