A template generator that generates values from an initial value by applying a computation to the previous value a given number of times.
More...
template<typename T, typename Computer>
class bnmf_algs::util::Generator< T, Computer >
A template generator that generates values from an initial value by applying a computation to the previous value a given number of times.
A generator object is very similar to python generator expressions in that it generates values from an initial value by applying a function repeatedly. Only the most recently computed value is stored and returned.
After the specified number of values are generated by repeatedly applying the computer function/functor, Generator object gets consumed and cannot generate any more values. Hence, to generate more values, a new Generator is required. For example,
void increment(size_t step, int& prev) {
++prev;
}
Generator<int, decltype(&increment)> gen(0, 50, increment);
for (auto num : gen) {
}
for (auto num : gen) {
new_numbers.push_back(num);
}
Since Generator object provides begin() and end() methods, it can be used with range-based for loops as seen in the previous example. Regular iterator-based for loops are also supported:
Op increment;
Generator<int, Op> gen(0, 50, increment);
for (auto it = gen.begin(); it != gen.end(); ++it) {
}
- Template Parameters
-
T | Type of the values to generate. |
Computer | Type of the computer functor/function/etc. to use. |
template<typename T, typename Computer>
Return the iterator pointing to the previously computed value.
Note that since only the most recently computed value is stored, the semantics for begin() is not the same STL container::begin(). After an iterator is incremented, the next value is computed and the previous value is forgotten.
All the returned begin iterators point to the same values. Hence, once a copy of a begin iterator is incremented and hence the pointed values are updated, all the subsequent calls to begin() will return iterators pointing to these updated values.
An increment to any of the iterators update the values pointed by all the iterators. Hence, once the total number of calls to increment operator on iterators is equal to iter_count, all the iterators are equal to Generator::end().
Note that incrementing any of the iterators beyond Generator::end() still produces new values. However, after that point, it is no longer possible to make equivalence checks against Generator::end(). Hence, in such a case iterators must be handled manually.
- Returns
- Iterator pointing to the most recently computed value.