使用地图内的std :: unique_ptr作为键

5 c++ maps

我正在使用Visual Studio2012。我有一张地图,看起来像这样:

std::map<std::string,std::map<std::unique_ptr<sf::Sound>,std::unique_ptr<sf::SoundBuffer>>> listSoundContainer;
Run Code Online (Sandbox Code Playgroud)

我正在尝试像这样插入数据:

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)));               
}
Run Code Online (Sandbox Code Playgroud)

并且即时通讯在编译时出现以下错误:

Microsoft Visual Studio 11.0 \ vc \ include \ utility(182):错误C2248:'std :: unique_ptr <_Ty> :: unique_ptr':无法访问类'std :: unique_ptr <_Ty>'1>中声明的私有成员1 >
[1> _Ty = sf ::声音1>] 1> c:\程序文件(x86)\ Microsoft Visual Studio 11.0 \ vc \ include \ memory(1447):请参见'std :: unique_ptr <_Ty>的声明: :unique_ptr'1> 1> [1> _Ty = sf :: Sound 1>] 1> c:\ program files(x86)\ microsoft visual studio 11.0 \ vc \ include \ xmemory0(617):请参见对功能模板的引用实例化'std :: pair <_Ty1,_Ty2> :: pair(std :: pair <_Ty1,_Ty2> &&,void **)'编译为1>,其中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插入数据并遇到相同的问题。我想念什么?我已经尝试解决这个问题两个小时了,无法解决。

我实际上可以通过不使用智能指针来解决此问题:

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));
Run Code Online (Sandbox Code Playgroud)

men*_*dal 2

查看模板定义std::map

template<
    class Key,
    class T,
    class Compare = std::less<Key>,
    class Allocator = std::allocator<std::pair<const Key, T> >
> class map;
Run Code Online (Sandbox Code Playgroud)

现在让我们看看如何尝试实例化它:

std::map<
    std::string, 
    std::map<
        std::unique_ptr<sf::Sound>, 
        std::unique_ptr<sf::SoundBuffer>
    >
> 
listSoundContainer
Run Code Online (Sandbox Code Playgroud)

这里的问题是 astd::unique_ptr<sf::Sound>不能充当键。

你似乎想做的是列出某种清单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
Run Code Online (Sandbox Code Playgroud)