您好,我使用 lambda 函数在 C++11 中创建了一个 future vector 。
vector<double> v = { 0, 1.1, 2.2, 3.3, 4.4, 5.5 };
auto K = [=](double z){
double y=0;
for (const auto x : v)
y += x*x*z;
return y;
};
vector<future<double>> VF;
for (double i : {1,2,3,4,5,6,7,8,9})
VF.push_back(async(K,i));
它运行成功,但是当我尝试通过 for_each 调用检索值时,我遇到了一个我不理解的编译错误。
for_each(VF.begin(), VF.end(), [](future<double> x){cout << x.get() << " "; });
这些值是通过旧式 for 循环成功获取的:
for (int i = 0; i < VF.size(); i++)
cout << VF[i].get() << " ";
为什么我不能使用 for_each 函数?我正在使用 Visual Studio 2013 并尝试使用 INTEL (V16) 编译器。
最佳答案
下面是使用两个合法选项之一的测试代码:
#include <vector>
#include <future>
#include <iostream>
#include <algorithm>
using namespace std;
// option 1 : pass a reference to the future
void test1()
{
vector<double> v = { 0, 1.1, 2.2, 3.3, 4.4, 5.5 };
auto K = [=](double z){
double y=0;
for (const auto x : v)
y += x*x*z;
return y;
};
vector<future<double>> VF;
for (double i : {1,2,3,4,5,6,7,8,9})
VF.push_back(async(K,i));
for_each(VF.begin(), VF.end(), [](future<double>& x){cout << x.get() << " "; });
}
// option 2 : store shared_futures which allow passing copies
void test2()
{
vector<double> v = { 0, 1.1, 2.2, 3.3, 4.4, 5.5 };
auto K = [=](double z){
double y=0;
for (const auto x : v)
y += x*x*z;
return y;
};
vector<shared_future<double>> VF;
for (double i : {1,2,3,4,5,6,7,8,9})
VF.push_back(async(K,i));
for_each(VF.begin(), VF.end(), [](shared_future<double> x){cout << x.get() << " "; });
}
关于c++ - c++ 11中的 future vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36596398/