In STL/Boost, is there a ready-made output iterator that only counts the number of times it's incremented? When an algorithm does *iter = value
, the value would simply be discarded.
If not, then rolling my own seems easy enough. Although it might be useful to others if someone posted an example of such an iterator.
No such iterator exists in standard C++, and to the best of my knowledge no Boost iterator has this exact functionality. There are plenty of ways that you could do this using those libraries without having to roll your own, though. For example, using Boost's function_output_iterator
, you could build a counter like this:
struct Counter {
size_t* out;
explicit Counter(size_t* where) : out(where) {
// Handled in initializer list
}
/* Either make this a template, or make the class itself a template. */
template <typename T> void operator()(T& value) {
++ *out;
}
};
This functor type takes in a pointer to a counter variable, and then whenever its operator()
is invoked increments the counter. If you then wrap this in a function_output_iterator
, as seen here:
size_t count;
your_algorithm(begin, end,
boost::make_function_output_iterator(Counter(&count)));
Then whenever the created iterator is written to, your operator()
will get called and the counter will get incremented.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With