C++11 中的未来向量
vector of future in c++11
嗨,我在 C++11 中使用 lambda 函数创建了一个未来的向量。
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() << " "; });
}
你不能复制期货。
要么使用引用,要么存储shared_future
。
将删除未来的复制构造函数,因此无法复制它们。使用参考:
for_each(VF.begin(), VF.end(), [](future<double>& x){cout << x.get() << " "; });
^~~~~ !
相关文章:
- 写入向量<向量<bool>>
- 函数向量_指针有不同的原型,我可以构建一个吗
- std::向量与传递值的动态数组
- 将值指定给向量(2D)的向量中的某个位置
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 在Linux中哪里可以找到互斥、未来等的源代码
- 如何使用向量的template_back函数
- 尝试通过多个向量访问变量时,向量下标超出范围
- 如何通过派生类函数更改基类中的向量
- C++从另一个类访问公共静态向量的正确方法是什么
- 如何将ampl中的集合表示为c++中的向量
- 变量没有改变?通过向量的函数调用
- 迭代时从向量和内存中删除对象
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 计算排序向量的向量中唯一值的计数
- 如何将基于范围的 for 循环与未来的<T>向量一起使用
- C++11 中的未来向量
- 优雅地避免了未来C++向量元素的值初始化
- 对象的向量搜索未来对象的使用?