i wrote the code in following way
#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;
}
i passed 2D map m reference to hi function and i updated but it not reflecting in main function. When i print m.size() it printing zero only.how can i pass the 2D map reference to function using thread?
The thread constructor will copy its arguments, so one solution is to use std::ref
:
thread t = thread (hi, std::ref(m));
This creates a wrapper object that behaves as a reference. The wrapper itself will be copied (semantically, in reality the copy may be elided), but the underlying map will not. So overall, it will act as if you had passed by reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With