Parallel invocation of algorithms

Suppose you have a data series given by a pair of input iterators and you want to calculate some statistics on this data series. For example, you are asked to return the average value of the series.

With forward iterators, this would be easy: accumulate divided by distance. However, once you have calculated accumulate with input iterators, you have already lost the possibility to calculate distance because you cannot recalculate on the same data (the begin iterator will be equal to the end iterator after just one step, so the calculated distance will always be 1).

I understand that it can be calculated using a custom accumulate operation. Is there a better way to address this problem? I would like to be able to easily run several algorithms in parallel on the same iterator range and obtain the results as a tuple.

Another example: calculate inner products of the input sequence with several different vectors. Here you will need to zip all the reference vectors into one matrix and iterate over the rows of the matrix. This looks like a very cumbersome solution for a simple problem.

Any thoughts?
So basically you want something like
1
2
3
4
5
6
template <typename F, typename It>
F::result_t apply(F f, It begin, It end){
    for (; begin != end; ++begin)
        f(*begin);
    return f.result();
}

And a particular usage of such a function could be
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class MeanCalculator{
    double sum = 0;
    size_t count = 0;
public:
    typedef double result_t;
    void operator()(double x){
        this->sum += x;
        this->count++;
    }
    result_t result() const{
        return this->sum / this->count;
    }
};

auto result = apply(MeanCalculator(), v.begin(), v.end());

You should be able to build on top of this a variadic template function that accepts some number of functors and returns an std::tuple with each result_t.
Last edited on
As I said, this loop is already implemented by accumulate. So if accumulate is the way to go, I need a framework to construct a composite parallel functor for accumulate. I can write this myself with some effort but I feel that it should have already been written — it seems obvious that anybody would need such a thing sooner or later.
Topic archived. No new replies allowed.