2017-10-17 148 views
1

我有一個函數的是具有矢量如何在C++ 11將來多次使用get()或如何獲得向量值?

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... 

是的,我可以」 t使用得到多次,所以我使用results.push_back(std::move(f));行,如果我沒有評論f.wait()行結果是一樣的錯誤。

除此之外的所有工作。我怎樣才能獲得我的「makecode」函數所做的向量?

+0

我想用'的std :: shared_future'。 http://en.cppreference.com/w/cpp/thread/shared_future – alfC

+1

你用'n'空的初始化了期貨向量,並且將更多的東西推到後面 –

+0

'std :: vector <...> results(n);'用'n'元素創建一個'vector'。你沒有對他們做任何事情(你只是增加更多),所以「未來」與任何事物都沒有關聯。 – Kevin

回答

1

當你創建你的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]); 
}