Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output iterator that only counts the number of increments?

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.

like image 371
Emile Cormier Avatar asked Nov 06 '22 02:11

Emile Cormier


1 Answers

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!

like image 167
templatetypedef Avatar answered Nov 15 '22 05:11

templatetypedef