Hey guys!
I'm just getting into c++ and after learning stuff about reference and value pass I've come across a problem.
So basically I'm trying to copy a map and I do so in my method. So far the size of the 2 maps are the same.
The problem comes when I insert some new values into the original map because it doesn't change the copied map.
So my question is how do I copy/pass a map, with the new map being a real copy and when the original changes, the copied version does so.
I'll attach the code that I was working on.
The code:
#include <iostream>
#include <map>
using namespace std;
map<string, int> passMapByReference(map<string, int>& temp_map){
return temp_map;
}
void printMap(map<string, int>& temp_map ){
cout << temp_map.size() << endl;
}
int main()
{
map<string, int> copyMap;
map<string, int> map;
map["asd"] = 1;
map["dsa"] = 2;
printMap(map);
copyMap = passMapByReference(map);
printMap(copyMap);
map["ksdbj"] = 3;
map["askdnijabsd"] = 4;
printMap(map);
//this should print 4
printMap(copyMap);
return 0;
}
The output:
2
2
4
2