The output of an iterator that takes into account only the number of increments?

Is there a ready-made output iterator in STL / Boost that counts the number of times it increased? When the algorithm executes *iter = value, the value will simply be discarded.

If not, rolling my own seems easy enough. Although it may be useful for others, if someone posted an example of such an iterator.

+5
source share
2 answers

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) {
        // 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 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!

+4
source

Yeah. In boost:

Iterator Count

-1
source

All Articles