如何在 c++ 11 futures 中多次使用 get() 或如何获取向量值

How to use get() multiple times in c++ 11 future or how to get a vector values?

本文关键字:获取 向量 get 何获取 c++ futures      更新时间:2023-10-16

>我有一个函数,什么是向量返回

    std::vector<int> makecode(std::vector<std::string> row)

和我的程序:

    std::vector<std::vector<std::string>> data(n);
    std::vector<std::future<std::vector<int>>> results(n);
    for(size_t i =0;i<n;++i){
         results.push_back(std::async(std::launch::async,makecode, data[i]));
    }
    for(std::future<std::vector<int>>& f : results){
         f.wait();
         f.get();;
    }

我得到这个异常:

what(): No associated state Error...

是的,我不能多次使用 get,所以我使用results.push_back(std::move(f));行,如果我不f.wait()行发表评论,结果是相同的错误。

除了这个,一切都在工作。 如何获取由我的"生成代码"函数制作的向量?

创建vector时,使用n元素对其进行初始化。这些未来与任何东西都没有关联,所以当你试图wait它们时,他们会抛出一个异常。要修复,请更改:

std::vector<std::future<std::vector<int>>> results(n);

std::vector<std::future<std::vector<int>>> results;

或者分配给每个元素而不是调用push_back

std::vector<std::future<std::vector<int>>> results(n);
for(size_t i =0;i<n;++i){
     results[i] = std::async(std::launch::async,makecode, data[i]);
}