Vector of the future in C ++ 11

Hi, I created a vector of the future in C ++ 11 using a lambda function.

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

It worked successfully, but when I tried to get the values ​​via the for_each call, I got a compilation error that I don't understand.

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

Values ​​were successfully obtained by the old style for the loop:

  for (int i = 0; i < VF.size(); i++) cout << VF[i].get() << " "; 

Why couldn’t I use the for_each function? I used Visual Studio 2013, also trying the INTEL compiler (V16).

+5
source share
3 answers

Here is the test code presented using one of two options:

 #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() << " "; }); } 
+1
source

You cannot copy futures.

Either use the link or save shared_future .

+2
source

Copy the constructor of the future is deleted, so you can not copy them. Use the link:

 for_each(VF.begin(), VF.end(), [](future<double>& x){cout << x.get() << " "; }); ^~~~~ ! 
+1
source

Source: https://habr.com/ru/post/1247029/


All Articles