There is no such iterator in standard C ++, and as far as I know, Boost iterator has this exact functionality. There are many ways you could do this using these libraries, but not folding your own. For example, using Boost function_output_iterator, you can build a counter as follows:
struct Counter {
size_t* out;
explicit Counter(size_t* where) : out(where) {
}
template <typename T> void operator()(T& value) {
++ *out;
}
};
This type of functor takes a pointer to a counter variable, and then whenever it is called operator(), the counter is incremented. If you then wrap this in function_output_iterator, as shown here:
size_t count;
your_algorithm(begin, end,
boost::make_function_output_iterator(Counter(&count)));
Then, whenever the created iterator is written, your call operator()will be called and the counter will increment.
Hope this helps!
source
share