c++ 如何优雅地将 c++17 并行执行与计算整数的 for 循环一起使用?

2021-12-30 00:00:00 parallel-processing c++ c++17

我可以

std::vector<int> a;
a.reserve(1000);
for(int i=0; i<1000; i++)
    a.push_back(i);
std::for_each(std::execution::par_unseq, std::begin(a), std::end(a), [&](int i) {
  ... do something based on i ...
});

但是有没有一种更优雅的方式来创建一个并行化版本的 for(int i=0; i<n; i++) 不需要我先用升序整数填充一个向量?

but is there a more elegant way of creating a parallelized version of for(int i=0; i<n; i++) that does not require me to first fill a vector with ascending ints?

推荐答案

您可以使用 std::generate 来创建向量 {0, 1, ..., 999}

You could use std::generate to create a vector {0, 1, ..., 999}

std::vector<int> v(1000);
std::generate(v.begin(), v.end(), [n = 0] () mutable { return n++; });

有一个接受 ExecutionPolicy 的重载,因此您可以将上述内容修改为

There is an overload that accepts an ExecutionPolicy so you could modify the above to

std::vector<int> v(1000);
std::generate(std::execution::par, v.begin(), v.end(), [n = 0] () mutable { return n++; });

相关文章