Skip to content

Commit a08c543

Browse files
committed
Counting aggregator
1 parent 99e99cf commit a08c543

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

inc/aggregators.hpp

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,26 @@ tup_aggregate_to(generator<std::tuple<TKey, TVal>> &gen,
6363
}
6464
return out;
6565
}
66+
67+
/**
68+
* \brief Counts the amount of elements in the generator.
69+
*
70+
* Each element is extracted from the generator. These values are not
71+
* recoverable. Only values left in the generator are counted. Afterwards, the
72+
* generator will be empty.
73+
*
74+
* \tparam T The type of values contained in the generator.
75+
* \param[in,out] gen The generator to iterate over.
76+
* \returns The amount of elements in the generator.
77+
*/
78+
template <typename T> size_t count(generator<T> &gen) {
79+
size_t cnt = 0;
80+
while (gen) {
81+
gen();
82+
cnt++;
83+
}
84+
return cnt;
85+
}
6686
} // namespace fpgen
6787

6888
#endif

test/src/test_aggreg.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,3 +67,14 @@ TEST(aggregate, map) {
6767
EXPECT_EQ(34, res[34]);
6868
EXPECT_EQ(res.size(), 9);
6969
}
70+
71+
TEST(aggregate, count_empty) {
72+
auto gen = a_empty();
73+
gen();
74+
EXPECT_EQ(0, fpgen::count(gen));
75+
}
76+
77+
TEST(aggregate, count) {
78+
auto gen = values();
79+
EXPECT_EQ(10, fpgen::count(gen));
80+
}

0 commit comments

Comments
 (0)