[llvm] 7e71877 - [ADT] Wrapper for `std::accumulate` accepting a `range`. (#158702)

via llvm-commits llvm-commits at lists.llvm.org
Tue Sep 16 07:20:15 PDT 2025


Author: Mircea Trofin
Date: 2025-09-16T07:20:10-07:00
New Revision: 7e71877835a567ada4d0e57413a5f64de3545033

URL: https://github.com/llvm/llvm-project/commit/7e71877835a567ada4d0e57413a5f64de3545033
DIFF: https://github.com/llvm/llvm-project/commit/7e71877835a567ada4d0e57413a5f64de3545033.diff

LOG: [ADT] Wrapper for `std::accumulate` accepting a `range`. (#158702)

Added: 
    

Modified: 
    llvm/include/llvm/ADT/STLExtras.h
    llvm/unittests/ADT/STLExtrasTest.cpp

Removed: 
    


################################################################################
diff  --git a/llvm/include/llvm/ADT/STLExtras.h b/llvm/include/llvm/ADT/STLExtras.h
index 099bef288b953..02705fbc8f2c4 100644
--- a/llvm/include/llvm/ADT/STLExtras.h
+++ b/llvm/include/llvm/ADT/STLExtras.h
@@ -35,6 +35,7 @@
 #include <iterator>
 #include <limits>
 #include <memory>
+#include <numeric>
 #include <optional>
 #include <tuple>
 #include <type_traits>
@@ -1694,6 +1695,12 @@ template <typename R> constexpr size_t range_size(R &&Range) {
     return static_cast<size_t>(std::distance(adl_begin(Range), adl_end(Range)));
 }
 
+/// Wrapper for std::accumulate.
+template <typename R, typename E> auto accumulate(R &&Range, E &&Init) {
+  return std::accumulate(adl_begin(Range), adl_end(Range),
+                         std::forward<E>(Init));
+}
+
 /// Provide wrappers to std::for_each which take ranges instead of having to
 /// pass begin/end explicitly.
 template <typename R, typename UnaryFunction>

diff  --git a/llvm/unittests/ADT/STLExtrasTest.cpp b/llvm/unittests/ADT/STLExtrasTest.cpp
index 9fda0d912a2f5..d355a59973f9a 100644
--- a/llvm/unittests/ADT/STLExtrasTest.cpp
+++ b/llvm/unittests/ADT/STLExtrasTest.cpp
@@ -1602,6 +1602,16 @@ TEST(STLExtrasTest, Fill) {
   EXPECT_THAT(V2, ElementsAre(Val, Val, Val, Val));
 }
 
+TEST(STLExtrasTest, Accumulate) {
+  EXPECT_EQ(accumulate(std::vector<int>(), 0), 0);
+  EXPECT_EQ(accumulate(std::vector<int>(), 3), 3);
+  std::vector<int> V1 = {1, 2, 3, 4, 5};
+  EXPECT_EQ(accumulate(V1, 0), std::accumulate(V1.begin(), V1.end(), 0));
+  EXPECT_EQ(accumulate(V1, 10), std::accumulate(V1.begin(), V1.end(), 10));
+  EXPECT_EQ(accumulate(drop_begin(V1), 7),
+            std::accumulate(V1.begin() + 1, V1.end(), 7));
+}
+
 struct Foo;
 struct Bar {};
 


        


More information about the llvm-commits mailing list