Implementing Parallel std::count_if() and std::copy_if()
Learn how to implement the std::count_if() function and parallelize the std::copy_if() operation.
We'll cover the following...
Implementation of std::count_if()
A nice thing about divide and conquer is that it can be applied to many problems. We can easily use the same technique to implement a parallel version of std::count_if()
, with the difference being that we need to accumulate the returned value, like this:
Press + to interact
template <typename It, typename Pred>auto par_count_if(It first, It last, Pred pred, size_t chunk_sz) {auto n = static_cast<size_t>(std::distance(first, last));if (n <= chunk_sz)return std::count_if(first, last, pred);auto middle = std::next(first, n / 2);auto fut = std::async(std::launch::async, [=, &pred] {return par_count_if(first, middle, pred, chunk_sz);});auto num = par_count_if(middle, last, pred, chunk_sz);return num + fut.get();}
As you can see, the only difference here is that we need to sum ...