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/29887185/

相关文章:

c++ - 我可能会在 Visual Studio 2005 中收到此 "Symbol not defined"错误的原因有哪些(包括屏幕截图)

android - Google maps v2 android,点击时信息窗口没有以默认突出显示颜色突出显示?

javascript - 传单 Angular Directive(指令)中的 KML

javascript - 使用 leafletjs 创建箭头

java - Android map 应用强制关闭设备

c++立陶宛语,如何获得比ascii更多的内容

c++ - 临时打印地址?

c++ - 是否可以使用基类和派生类来实现 Qt Application Plugin?

c++ - 是只需要一次 volatile 还是从MMIO mmap'd地址指针派生的每个指针上都需要volatile?

blackberry - 使用 BlackBerry Maps API 是否涉及任何许可费用