c ++ 11中未来的向量

Giu*_*evi 8 c++ foreach future c++11

嗨我使用lambda函数在C++ 11中创建了一个未来的向量.

 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));
Run Code Online (Sandbox Code Playgroud)

它成功地工作但当我尝试通过for_each调用检索值时,我获得了一个我不理解的编译错误.

 for_each(VF.begin(), VF.end(), [](future<double> x){cout << x.get() << " "; });
Run Code Online (Sandbox Code Playgroud)

通过旧样式for循环成功获取值:

 for (int i = 0; i < VF.size(); i++)
    cout << VF[i].get() << " ";
Run Code Online (Sandbox Code Playgroud)

为什么我无法使用for_each函数?我正在使用Visual Studio 2013尝试使用INTEL(V16)编译器.

Ric*_*ges 6

这是使用两个合法选项之一显示的测试代码:

#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() << " "; });
}
Run Code Online (Sandbox Code Playgroud)