3
votes

I am using std::unordered_map for the first time and am having a problem inserting into the map I have created.

ClassA header:

Class ClassA
{
public:
    void func();
private:
    std::unordered_map<std::string, std::shared_ptr<ClassB>> map;
}

ClassA cpp:

void ClassA::func()
{
    map = std::unordered_map<std::string, std::shared_ptr<ClassB>>();
    map.insert("string", std::make_shared<ClassB>());
}

I am getting error c2664 std::_List_iterator<_Mylist> std::_Hash<_Traits>::insert(std::_List_const_iterator<_Mylist>,std::pair<_Ty1,_Ty2> &&)' : cannot convert parameter 1 from 'const char [17]' to 'std::_List_const_iterator<_Mylist>'

Any ideas?

2

2 Answers

3
votes

The problem is not with the shared_ptr, but with the string key. Explicit instantiation will solve this problem. You also need to insert a pair consisting of the key and the value, not a key and a value seperately:

map.insert(std::make_pair (std::string("string"), std::make_shared<ClassB>()));

See also this related answer for a more novel, albiet more complex solution.

1
votes

initializer_list can solve your issue too.

map.insert( {"string", std::make_shared<ClassB>()} );