如何简化此代码?

刘君逸*_*刘君逸 0 c++ concurrency templates c++11

我在我的程序中测试并发性并编写以下代码

vector<unique_ptr<future<double>>> results;
for (unsigned i = 0; i != 16; ++i)
{
     unique_ptr <future<double>> result(new future<double >{ async(once) });
     results.push_back(move(result));
}
auto ave = (results[0]->get() + results[1]->get() + results[2]->get() +\
    results[3]->get() + results[4]->get() + results[5]->get() +\
    results[6]->get() + results[7]->get() + results[8]->get() + \
    results[9]->get() + results[10]->get() + results[11]->get() + \
    results[12]->get() + results[13]->get() + results[14]->get() + \
    results[15]->get()) / 16.0;
Run Code Online (Sandbox Code Playgroud)

once是一个不带参数并返回double的函数,例如,在[0,1]中返回一个随机数.平均16个结果.如果我平均100次,我发现代码真的是多余的.使用循环可能解决问题,但我不确定并发是否仍然有效,所以我徘徊如何简化代码?

Kon*_*lph 10

学习C++算法:

using type = unique_ptr<future<double>>;
auto mean = std::accumulate(results.begin(), results.end(), 0.0,
        [](double a, type const& b) { return a + b->get(); }) / results.length();
Run Code Online (Sandbox Code Playgroud)

  • (由于我急于发布错误的答案,显然*我*也应该学习C++算法,然后在这里发布......我现在已经纠正了) (2认同)