我在使用 std::future 和 std::async 返回 std::vector 时遇到问题。为什么
#include <iostream>
#include <vector>
#include <functional>
#include <future>
using namespace std;
int main(int argc, char** argv) {
int A = 10;
vector<future<int>> sumarray(A);
for(int i = 0; i < A; i++)
sumarray[i] = async( launch::async, [i] { return i; } );
for(int i = 0; i < A; i++)
cout << sumarray[i].get() << " ";
cout << endl;
}
Run Code Online (Sandbox Code Playgroud)
用 g++ -std=c++11 -pthread 编译,按预期打印
0 1 2 3 4 5 6 7 8 …