[llvm] [ADT] Wrapper for `std::accumulate` accepting a `range`. (PR #158702)
via llvm-commits
llvm-commits at lists.llvm.org
Mon Sep 15 11:03:10 PDT 2025
llvmbot wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-llvm-adt
Author: Mircea Trofin (mtrofin)
<details>
<summary>Changes</summary>
---
Full diff: https://github.com/llvm/llvm-project/pull/158702.diff
2 Files Affected:
- (modified) llvm/include/llvm/ADT/STLExtras.h (+6)
- (modified) llvm/unittests/ADT/STLExtrasTest.cpp (+11)
``````````diff
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 {};
``````````
</details>
https://github.com/llvm/llvm-project/pull/158702
More information about the llvm-commits
mailing list