std::unordered_map 插入错误shared_ptr C++

std::unordered_map insert error shared_ptr c++

本文关键字:ptr shared C++ 错误 map unordered std 插入      更新时间:2023-10-16

我是第一次使用 std::unordered_map,但在插入我创建的地图时遇到问题。

A 类标头:

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

A类CPP:

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

我收到错误 c2664 std::_List_iterator<_Mylist> std::_Hash<_Traits>:::insert(std::_List_const_iterator<_Mylist>,std::p air<_Ty1,_Ty2> &&)' :无法将参数 1 从"常量字符 [17]"转换为"std::_List_const_iterator<_Mylist>"

有什么想法吗?

问题不在于shared_ptr,而在于string键。 显式实例化将解决此问题。 您还需要插入一个由键和值组成的pair,而不是分别插入键和值:

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

另请参阅此相关答案,以获取更新颖、更复杂的解决方案。

>initializer_list也可以解决您的问题。

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