Daniel
Daniel

Reputation: 351

std::unordered_map insert error shared_ptr c++

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?

Upvotes: 5

Views: 8023

Answers (3)

Zipzap
Zipzap

Reputation: 39

Since you need to insert a pair to the map, you can also use emplace instead of insert, so it will construct the pair in-place with the given key and value. https://en.cppreference.com/w/cpp/container/unordered_map/emplace

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

Upvotes: 0

where23
where23

Reputation: 513

initializer_list can solve your issue too.

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

Upvotes: 2

John Dibling
John Dibling

Reputation: 101456

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.

Upvotes: 5

Related Questions