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

编程入门 行业动态 更新时间:2024-10-19 04:30:38
本文介绍了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 ++)的并行版本,而该版本不需要我先用升序的int填充向量?

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}

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循环一起使用?

本文发布于:2023-11-29 20:25:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647533.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   优雅

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!