[llvm] [ADT] Wrapper for `std::accumulate` accepting a `range`. (PR #158702)
Mircea Trofin via llvm-commits
llvm-commits at lists.llvm.org
Mon Sep 15 10:59:43 PDT 2025
https://github.com/mtrofin created https://github.com/llvm/llvm-project/pull/158702
None
>From dc3518fd4e5df00e00d34fa92cb0e49932f48dce Mon Sep 17 00:00:00 2001
From: Mircea Trofin <mtrofin at google.com>
Date: Mon, 15 Sep 2025 17:58:13 +0000
Subject: [PATCH] [ADT] Wrapper for `std::accumulate` accepting a `range`.
---
llvm/include/llvm/ADT/STLExtras.h | 6 ++++++
llvm/unittests/ADT/STLExtrasTest.cpp | 11 +++++++++++
2 files changed, 17 insertions(+)
diff --git a/llvm/include/llvm/ADT/STLExtras.h b/llvm/include/llvm/ADT/STLExtras.h
index 099bef288b953..155feb90bd94c 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,11 @@ 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> E range_accumulate(R &&Range, E Init) {
+ std::accumulate(Range.begin(), Range.end(), 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..ff1d413979bdc 100644
--- a/llvm/unittests/ADT/STLExtrasTest.cpp
+++ b/llvm/unittests/ADT/STLExtrasTest.cpp
@@ -1602,6 +1602,17 @@ TEST(STLExtrasTest, Fill) {
EXPECT_THAT(V2, ElementsAre(Val, Val, Val, Val));
}
+TEST(STLExtrasTest, Accumulate) {
+ EXPECT_EQ(range_accumulate(std::vector<int>(), 0), 0);
+ EXPECT_EQ(range_accumulate(std::vector<int>(), 3), 3);
+ std::vector<int> V1 = {1, 2, 3, 4, 5};
+ EXPECT_EQ(range_accumulate(V1, 0), std::accumulate(V1.begin(), V1.end(), 0));
+ EXPECT_EQ(range_accumulate(V1, 10),
+ std::accumulate(V1.begin(), V1.end(), 10));
+ EXPECT_EQ(range_accumulate(drop_begin(V1), 7),
+ std::accumulate(V1.begin(), V1.end(), 7) - V1[0]);
+}
+
struct Foo;
struct Bar {};
More information about the llvm-commits
mailing list