I have been trying to get back into C++ but have come across a problem that I have not managed to solve. In the example below I have created a struct Node and a class C. The class contains a map. The class has a get and a set function. The problem I face is that once I execute the get function, the value of the node changes. Below the output of the code below is:
4
32766
32766
As you can see, the value changes once I execute the set function. If anybody knows what the problem is please let me know.
Thanks.
#include <iostream>
#include <map>
using namespace std;
struct Node {
int value;
Node(int v):value(v){};
};
class C {
public:
map<int, Node*> m;
C() {};
void set(int key, int value) {
Node n = Node(value);
m.insert(pair<int,Node*>(key, &n));
}
int get(int key) {
return m[key]->value;
}
};
int main() {
C t = C();
t.set(1,4);
cout << t.m[1]->value << endl;
cout << t.get(1) << endl;
cout << t.m[1]->value << endl;
}