Skip to content

Commit c0bb63a

Browse files
committed
Added enumerate source
1 parent f359e83 commit c0bb63a

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

inc/sources.hpp

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ namespace fpgen {
2121
* \tparam Container The container type.
2222
* \param[in] cont The container to iterate over.
2323
* \returns A new generator which will iterate over the container.
24-
* \see fpgen::from_tup
24+
* \see fpgen::from_tup, fpgen::enumerate
2525
*/
2626
template <typename T, typename... TArgs,
2727
template <typename...> typename Container>
@@ -31,6 +31,31 @@ generator<T> from(const Container<T, TArgs...> &cont) {
3131
}
3232
}
3333

34+
/**
35+
* \brief Creates a generator over a data source, with indexing.
36+
*
37+
* The data source does not have to allow indexing, but it is recommended for
38+
* repeatable behaviour. If the index is not needed, use fpgen::from. The data
39+
* source should support iterating (using `std::begin` and `std::end`).
40+
*
41+
* \tparam T The type contained in the container.
42+
* \tparam TArgs Any other template parameters passed to the container.
43+
* \tparam Container The container type.
44+
* \param[in] cont The container to iterate over.
45+
* \returns A new generator which will iterate over the container using index
46+
* and value.
47+
* \see fpgen::from_tup, fpgen::enumerate
48+
*/
49+
template <typename T, typename... TArgs,
50+
template <typename...> typename Container>
51+
generator<std::tuple<size_t, T>> enumerate(const Container<T, TArgs...> &cont) {
52+
size_t i = 0;
53+
for (auto it = std::begin(cont); it != std::end(cont); ++it) {
54+
co_yield {i, *it};
55+
i++;
56+
}
57+
}
58+
3459
/**
3560
* \brief Creates a generator over an associative data source.
3661
*

test/src/test_sources.cpp

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,16 @@ TEST(sources, from_set) {
2828
EXPECT_TRUE(todo.empty());
2929
}
3030

31+
TEST(sources, enumerate_vector) {
32+
std::vector<char> values = { 'a', 'c', 'e', 'k', 'j', 't' };
33+
size_t prev = 0;
34+
for(auto v : fpgen::enumerate(values)) {
35+
EXPECT_EQ(std::get<0>(v), prev);
36+
EXPECT_EQ(values[prev], std::get<1>(v));
37+
prev++;
38+
}
39+
}
40+
3141
TEST(sources, from_map_tup) {
3242
std::map<std::string, std::string> map = {{"key 1", "value 1"},
3343
{"key 2", "value 2"},

0 commit comments

Comments
 (0)