C++ - 期货向量
C++ - vector of futures
以下代码无法编译:
#include <iostream>
#include <future>
#include <vector>
class Calculator {
public:
static int add(int a, int b)
{
return a + b;
}
};
int main(int argc, char* argv[]) {
std::vector<std::future<int>*> futures;
for(auto i = 0; i < 4; i++) {
auto future = new std::async(&Calculator::add, 1, 3);
futures.push_back(future);
}
for(auto i = 0; i < 4; i++) {
std::cout << futures[i]->get() << std::endl;
delete futures[i];
}
return 0;
}
我收到以下错误:
error: no type named 'async' in namespace 'std'
如何在期货向量上存储和调用 get((?
更新:
我正在使用C++ 11和一个没有矢量逻辑的异步示例工作正常。
由于对任何使用裸new
或delete
调用的代码(顺便说一下,这是一种很好的开发态度(,我重写了它以使用更"现代"的C++习语。
我不完全确定为什么你认为你需要存储指向期货的指针,这似乎不必要地使事情复杂化。无论如何,该代码片段new std::async()
给g++
带来了问题,我相信这就是您的错误no type named 'async' in namespace 'std'
的原因。
从技术上讲,这是正确的,std
中没有类型async
,因为async
是一个函数而不是一个类型。
修改后的代码如下:
#include <iostream>
#include <future>
#include <vector>
class Calculator {
public:
static int add(int a, int b) { return a + b; }
};
int main() {
std::vector<std::future<int>> futures;
for(auto i = 0; i < 4; i++)
futures.push_back(std::async(&Calculator::add, i, 3));
for(auto i = 0; i < 4; i++)
std::cout << futures[i].get() << std::endl;
return 0;
}
这编译和运行得很好,给出了我希望看到的结果:
pax> g++ -Wall -Wextra -pthread -std=c++11 -o testprog testprog.cpp
pax> ./testprog
3
4
5
6
相关文章:
- 写入向量<向量<bool>>
- 函数向量_指针有不同的原型,我可以构建一个吗
- std::向量与传递值的动态数组
- 将值指定给向量(2D)的向量中的某个位置
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 如何使用向量的template_back函数
- 尝试通过多个向量访问变量时,向量下标超出范围
- 如何通过派生类函数更改基类中的向量
- C++从另一个类访问公共静态向量的正确方法是什么
- 如何将ampl中的集合表示为c++中的向量
- 变量没有改变?通过向量的函数调用
- 迭代时从向量和内存中删除对象
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 计算排序向量的向量中唯一值的计数
- 矩阵向量乘法(cublasDgemv)返回零
- 一对向量构造函数:初始值设定项列表与显式构造
- 将结构向量排序为子组
- 在C++中调整向量中的索引
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么