Skip to content

Commit 7e71877

Browse files
authored
[ADT] Wrapper for std::accumulate accepting a range. (llvm#158702)
1 parent 2771d35 commit 7e71877

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

llvm/include/llvm/ADT/STLExtras.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
#include <iterator>
3636
#include <limits>
3737
#include <memory>
38+
#include <numeric>
3839
#include <optional>
3940
#include <tuple>
4041
#include <type_traits>
@@ -1694,6 +1695,12 @@ template <typename R> constexpr size_t range_size(R &&Range) {
16941695
return static_cast<size_t>(std::distance(adl_begin(Range), adl_end(Range)));
16951696
}
16961697

1698+
/// Wrapper for std::accumulate.
1699+
template <typename R, typename E> auto accumulate(R &&Range, E &&Init) {
1700+
return std::accumulate(adl_begin(Range), adl_end(Range),
1701+
std::forward<E>(Init));
1702+
}
1703+
16971704
/// Provide wrappers to std::for_each which take ranges instead of having to
16981705
/// pass begin/end explicitly.
16991706
template <typename R, typename UnaryFunction>

llvm/unittests/ADT/STLExtrasTest.cpp

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1602,6 +1602,16 @@ TEST(STLExtrasTest, Fill) {
16021602
EXPECT_THAT(V2, ElementsAre(Val, Val, Val, Val));
16031603
}
16041604

1605+
TEST(STLExtrasTest, Accumulate) {
1606+
EXPECT_EQ(accumulate(std::vector<int>(), 0), 0);
1607+
EXPECT_EQ(accumulate(std::vector<int>(), 3), 3);
1608+
std::vector<int> V1 = {1, 2, 3, 4, 5};
1609+
EXPECT_EQ(accumulate(V1, 0), std::accumulate(V1.begin(), V1.end(), 0));
1610+
EXPECT_EQ(accumulate(V1, 10), std::accumulate(V1.begin(), V1.end(), 10));
1611+
EXPECT_EQ(accumulate(drop_begin(V1), 7),
1612+
std::accumulate(V1.begin() + 1, V1.end(), 7));
1613+
}
1614+
16051615
struct Foo;
16061616
struct Bar {};
16071617

0 commit comments

Comments
 (0)