如何将基于范围的 for 循环与未来的<T>向量一起使用

How to use a range-based for loop with a vector of future<T>

本文关键字:未来 lt gt 一起 向量 循环 于范围 for 范围      更新时间:2023-10-16

我有一个程序,可以使用std::packaged_task<int()>计算不同线程中的一些值。我将通过get_future()从打包任务中获得std::future存储在向量中(定义为std::vector<std::future<int>>)。

当我计算所有任务的总和时,我使用 for 循环并且它正在工作:

// set up of the tasks
std::vector<std::future<int>> results;
// store the futures in results
// each task execute in its own thread
int sum{ 0 };
for (auto i = 0; i < results.size; ++i) {
sum += results[i].get();
}

但我宁愿使用基于范围的 for 循环:

// set up of the tasks
std::vector<std::future<int>> results;
// store the futures in results
// each task execute in its own thread
int sum{ 0 };
for (const auto& result : results) {
sum += result.get();
}

目前我收到一个编译错误:

program.cxx:83:16: error: 'this' argument to member function 'get' has type 'const std::function<int>', but function is not marked const
sum += result.get();
^~~~~~
/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/9.1.0/../../../../include/c++/9.1.0/future:793:7: note: 'get' declared here
get()
^

是否可以使用vectorfuture<int>的基于范围的 for 循环?

您需要从for (const auto& result : results)中删除conststd::future不提供编译器尝试调用的get的 const 限定版本,因为result是对const std::future的引用。

for (auto& result : results) {
sum += result.get();
}

做你想做的事。

get不是const,所以你需要非常量引用:

for (auto& result : results) {
sum += result.get();
}