How to do it...

To implement a parallel version of the map function, do the following:

  1. Define a function template that takes the begin and end iterators to a range and a function to apply to all the elements:
        template <typename Iter, typename F>        void parallel_map(Iter begin, Iter end, F f)        {        }
  1. Check the size of the range. If the number of elements is smaller than a predefined threshold (for this implementation, the threshold is 10,000), execute the mapping in a sequential manner:
        auto size = std::distance(begin, end);        if(size <= 10000)          std::transform(begin, end, begin, std::forward<F>(f));
  1. For larger ranges, split the work on multiple threads and let each thread map a part of the range. These parts should not overlap to avoid the ...

Get Modern C++ Programming Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.