开发者

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 = va开发者_如何学Pythonlue, 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!


Yep. In boost:

The counting iterator

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜