Hi I have created a vector of 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 retrieve the values via a for_each call I obtained a compilation error that I do not understand.
for_each(VF.begin(), VF.end(), [](future<double> x){cout << x.get() << " "; });
The values were successfully obtained by an old style for loop:
for (int i = 0; i < VF.size(); i++)
cout << VF[i].get() << " ";
Why I was not able to use the for_each function ? I was using Visual Studio 2013 trying also the INTEL ( V16) compiler.
A vector is a sequence container class that implements dynamic array, means size automatically changes when appending elements. A vector stores the elements in contiguous memory locations and allocates the memory as needed at run time.
(since C++11) The class template std::future provides a mechanism to access the result of asynchronous operations: An asynchronous operation (created via std::async, std::packaged_task, or std::promise) can provide a std::future object to the creator of that asynchronous operation.
Once you use the get() function on a future, it will wait until the result is available and return this result to you once it is. The get() function is then blocking.
Here is the test code presented using either of the two legal 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() << " "; });
}
You can't copy futures.
Either use a reference, or store a shared_future
.
Copy constructor of future is deleted, so you cannot copy them. Use reference:
for_each(VF.begin(), VF.end(), [](future<double>& x){cout << x.get() << " "; });
^~~~~ !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With