c++ - 如何简化这段代码?

标签 c++ templates c++11 concurrency

我在我的程序中测试并发并写了下面的代码

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;

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

最佳答案

了解 C++ algorithms :

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();

关于c++ - 如何简化这段代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27944204/

相关文章:

C++ 线程 : what does join do exactly?

c++ - 如何从 Int2Type 构建 Type2Int?

c++ - 三个原子变量上的 CompareAndExchange

c++ - 虚拟继承的优势

c++ - 这个 for 循环可以用预处理器完成吗?

c++ - 模板的实例化会导致二进制代码重复,编译器会阻止它吗?

C++ - 如何将 JSON 写回文件

c++ - 将调试语句重定向到 stderr 时出现奇怪的情况

python - 通过 SWIG 传递函数指针数组

c++ - enable_if 结构体定义和默认模板参数