c++ 如何优雅地将 c++17 并行执行与计算整数的 for 循环一起使用? [英] c++ how to elegantly use c++17 parallel execution with for loop that counts an integer?

查看:29
本文介绍了c++ 如何优雅地将 c++17 并行执行与计算整数的 for 循环一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以

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++; });

这篇关于c++ 如何优雅地将 c++17 并行执行与计算整数的 for 循环一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆