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

标签 c++ multithreading c++11 reference

我是这样写代码的

#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 map m 引用传递给 hi 函数并进行了更新,但它没有反射(reflect)在主函数中。当我打印 m.size() 时,它只打印零。我如何使用线程将 2D map 引用传递给函数?

最佳答案

线程构造函数将复制它的参数,所以一种解决方案是使用 std::ref :

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

这将创建一个作为引用的包装器对象。包装器本身将被复制(语义上,实际上拷贝可能被省略),但底层映射不会。所以总的来说,它就像您通过引用传递一样。

关于c++ - 如何使用 std::threads 将多维映射的引用传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17818316/

相关文章:

c# - 无法重现 : C++ Vector performance advantages over C# List performance

带定时器的 Android(Java) 生产者/消费者

c++ - 在构造函数中初始化静态函数指针

c++ - static_assert 如果声明了类型

c++ - 在 Eclipse for C++ 中更改可执行文件名称

c++ - 动态添加一行到 std::string 二维 vector 数组

c++ - 如何从复制赋值运算符调用复制构造函数?

android - Realm 模型从其他线程更新,但应该通知适配器

c++ - 为每次 c++ 创建一个障碍

c++ - 应用程序的一个实例,平台无关,C++11