autr
March 20, 2017, 8:07pm
#1
Hi, pretty basic but struggling to get this right.
If I have a map like so:
map<string, shared_ptr<MyClass>> mapped;
How can I add a pair to it? I’m trying…
mapped.insert(pair<string, shared_ptr<MyClass>>("name", element));
mapped.insert(make_pair("name", element));
etc
Thanks!
arturo
March 20, 2017, 8:19pm
#2
you can simply do:
mapped["name"] = make_shared<MyClass>();
or
mapped.insert(make_pair("name", make_shared<MyClass>()));
1 Like
autr
March 21, 2017, 10:52am
#4
Though I take it element goes in the constructor like so?
mapped["name"] = make_shared<MyClass>(element);
mapped.insert(make_pair("name", make_shared<MyClass>(element)));
I am getting No matching constructor for initialization of ‘MyClass’
autr
March 21, 2017, 10:56am
#5
It is done like so (summary):
void setup(MyClass * element) {
mapped["name"] = make_shared<MyClass>(element);
}
map<string, shared_ptr<MyClass>> mapped;
MySubClass * element = new MySubClass();
setup(element);
autr
March 21, 2017, 11:20am
#7
Ah OK, think I’ve got it, but now I have a problem of trying to return both the Derived class, and also add a shared_ptr with the Base class to the map. ie.
MySubClass & addChild(string name) {
MySubClass * element = new MySubClass(name);
mapped[name] = shared_ptr<MyClass>(element);
return * group;
}
Memory error…
arturo
March 21, 2017, 11:27am
#8
make_shared is already the constructor for MyClass no need to pass a pointer but if you have a constructor with parameters then you can call:
mapped[name] = make_shared<MyClass>(name);
for subclasses you can also do:
mapped[name] = make_shared<MySubClass>(name);
the way you did it finally is correct too. not sure what’s group in your last example so it’s hard to know what might be going on
autr
March 23, 2017, 11:01am
#9
Thanks, I got it working in the end but I think I have much bigger problems now. Would be great to get your help in the thread I’m just making (it’s to do with shared_ptrs).