簡體   English   中英

如何使用std :: threads將多維映射的引用傳遞給函數

[英]how to pass reference of multidimensional map to a function with std::threads

我按照以下方式編寫代碼

#include <iostream>
#include <thread>
#include <map>
using namespace std;
void hi (map<string,map<string,int> > &m ) {
   m["abc"]["xyz"] =1;
   cout<<"in hi";
}
int main() {
   map<string, map<string, int> > m;
   thread t = thread (hi, m);
   t.join();
   cout << m.size();
   return 0;
}

我通過2D地圖m參考hi函數,我更新但它沒有反映在main函數中。 當我打印m.size()時它只打印零。我可以使用線程將2D地圖引用傳遞給函數嗎?

線程構造函數將復制其參數,因此一種解決方案是使用std::ref

thread t = thread (hi, std::ref(m));

這將創建一個作為引用的包裝器對象。 包裝器本身將被復制(在語義上,實際上可以省略副本),但底層地圖不會。 總的來說,它會像你通過引用一樣傳遞。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM