I want to set up an easy workaround for parallelized index-based for-loops using std::views
.
For running in sequence the code looks like this:
int main() {
//pseudo-random numbers
random_device rd;
default_random_engine eng(rd());
uniform_int_distribution<int> distr(0, 100);
auto r = ranges::views::iota(0, 10);
vector<double> v(10, 1);
for_each(r.begin(), r.end(), [&](int i) {v[i] = distr(eng); });
for (auto&& i : v) cout << i << " "; cout << endl;
}
This works fine. I am using the standard version of std::for_each()
, not the one in the ranges
namespace, because those don't have the execution policies. Now the parallel version. Only difference:
for_each(execution::par, r.begin(), r.end(), [&](int i) {v[i] = distr(eng); });
MSVC gives an error:
error C2338: Parallel algorithms require forward iterators or stronger
I found a similar issue here: Using ranges::view::iota in parallel algorithms and I implemented the solution offered there:
auto r = views::iota(0) | views::take(10);
vector<double> v(10, 1);
auto input_range = ranges::common_view(r);
for_each(execution::par, ranges::begin(input_range), ranges::end(input_range), [&](int i) {v[i] = distr(eng); });
for (auto&& i : v) cout << i << " "; cout << endl;
However, I am still facing the error
error C2338: Parallel algorithms require forward iterators or stronger.
Does someone know whether there is a solution to this issue?