如何使用std :: threads将多维映射的引用传递给函数

nar*_*ren 3 c++ multithreading reference c++11

我按照以下方式编写代码

#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;
}
Run Code Online (Sandbox Code Playgroud)

我通过2D地图m参考hi函数,我更新但它没有反映在main函数中.当我打印m.size()时它只打印零.我可以使用线程将2D地图引用传递给函数吗?

jua*_*nza 8

线程构造函数将复制其参数,因此一个解决方案是使用std::ref:

thread t = thread (hi, std::ref(m));
Run Code Online (Sandbox Code Playgroud)

这将创建一个作为引用的包装器对象.包装器本身将被复制(在语义上,实际上可以省略副本),但底层地图不会.总的来说,它会像你通过引用一样传递.