[libcxx-commits] [libcxx] [libcxx] Optimize `ranges::fold_left_with_iter` for segmented iterators (PR #177853)

Connector Switch via libcxx-commits libcxx-commits at lists.llvm.org
Tue Feb 3 04:56:35 PST 2026


================
@@ -80,18 +82,22 @@ concept __indirectly_binary_left_foldable =
 struct __fold_left_with_iter {
   template <input_iterator _Ip, sentinel_for<_Ip> _Sp, class _Tp, __indirectly_binary_left_foldable<_Tp, _Ip> _Fp>
   [[nodiscard]] _LIBCPP_HIDE_FROM_ABI static constexpr auto operator()(_Ip __first, _Sp __last, _Tp __init, _Fp __f) {
-    using _Up = decay_t<invoke_result_t<_Fp&, _Tp, iter_reference_t<_Ip>>>;
+    using _Up        = decay_t<invoke_result_t<_Fp&, _Tp, iter_reference_t<_Ip>>>;
+    using __iter_ref = decltype(*__first);
 
     if (__first == __last) {
       return fold_left_with_iter_result<_Ip, _Up>{std::move(__first), _Up(std::move(__init))};
     }
 
     _Up __result = std::invoke(__f, std::move(__init), *__first);
-    for (++__first; __first != __last; ++__first) {
-      __result = std::invoke(__f, std::move(__result), *__first);
-    }
-
-    return fold_left_with_iter_result<_Ip, _Up>{std::move(__first), std::move(__result)};
+    ++__first;
+    auto __for_each_f = [&](__iter_ref __element) {
+      __result = std::invoke(__f, std::move(__result), std::forward<__iter_ref>(__element));
+    };
----------------
c8ef wrote:

Opened #179451.

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


More information about the libcxx-commits mailing list