c++ - 在 map 中使用 std::unique_ptr 作为键

标签 c++ maps

我正在使用 Visual Studio 2012。我的 map 如下所示:

std::map<std::string,std::map<std::unique_ptr<sf::Sound>,std::unique_ptr<sf::SoundBuffer>>> listSoundContainer;

我正在尝试插入这样的数据:
std::unique_ptr<sf::SoundBuffer> soundBuffer(new sf::SoundBuffer());
if (soundBuffer->loadFromFile("assets/sound/" + _fileName) != false)
{
    std::unique_ptr<sf::Sound> sound(new sf::Sound(*soundBuffer));
    typedef std::map<std::unique_ptr<sf::Sound>, std::unique_ptr<sf::SoundBuffer>> innerMap;
    listSoundContainer[_fileName].insert(innerMap::value_type(std::move(sound), std::move(soundBuffer)));               
}

我在编译时收到以下错误:

microsoft visual studio 11.0\vc\include\utility(182): error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>' 1> with 1>
[ 1> _Ty=sf::Sound 1> ] 1> c:\program files (x86)\microsoft visual studio 11.0\vc\include\memory(1447) : see declaration of 'std::unique_ptr<_Ty>::unique_ptr' 1> with 1> [ 1> _Ty=sf::Sound 1> ] 1> c:\program files (x86)\microsoft visual studio 11.0\vc\include\xmemory0(617) : see reference to function template instantiation 'std::pair<_Ty1,_Ty2>::pair(std::pair<_Ty1,_Ty2> &&,void **)' being compiled 1> with 1> [ 1>
_Ty1=const std::unique_ptr, 1> _Ty2=std::unique_ptr, 1> _Kty=std::unique_ptr, 1> _Ty=std::unique_ptr 1> ]



我也尝试使用 make_pair 插入数据,但存在同样的问题。我错过了什么?我已经尝试解决这个问题 2 个小时了,但我无法理解它。

我实际上可以通过不使用智能指针来解决这个问题:
sf::SoundBuffer* soundbuffer = new sf::SoundBuffer();
soundbuffer->loadFromFile(_file);
sf::Sound* sound = new sf::Sound(*soundbuffer);
typedef std::map<sf::SoundBuffer*, sf::Sound*> mapType;
listSound[_file].insert(mapType::value_type(soundbuffer, sound));

最佳答案

查看 std::map 的模板定义:

template<
    class Key,
    class T,
    class Compare = std::less<Key>,
    class Allocator = std::allocator<std::pair<const Key, T> >
> class map;

现在让我们看看你如何尝试实例化它:
std::map<
    std::string, 
    std::map<
        std::unique_ptr<sf::Sound>, 
        std::unique_ptr<sf::SoundBuffer>
    >
> 
listSoundContainer

这里的问题是 std::unique_ptr<sf::Sound>不能作为 key 。

您似乎想做的是制作某种列表 std::pair<std::unique_ptr<sf::Sound>, std::unique_ptr<sf::SoundBuffer>>
我建议改用这个:
std::map<
    std::string, 
    std::list<
        std::pair<
            std::unique_ptr<sf::Sound>, 
            std::unique_ptr<sf::SoundBuffer>
        >
    >
> 
listSoundContainer

关于c++ - 在 map 中使用 std::unique_ptr 作为键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52125792/

相关文章:

android - 生成 Google api key 时使用什么包

c++ - STL Map - 何时使用自定义比较器?

c++ - 将char指针数组传递给c++中的函数

c# - 使用头文件将 get/set 从 C# 转换为 C++

c++ - C++中派生类的对象可以被父类访问吗?

javascript - 使用 Google map JS SDK 添加没有纬度/经度的 map 标记?

opengl - 我想使用 openStreetMap 数据在 openGL 中渲染道路,我应该从哪里开始?

iphone - 如何在 iPhone 的 webview 中加载地址?

c++ - std::thread 在 vc++ 的析构函数中获取中止异常

c++ - 模板函数类型的后期绑定(bind) C++