【问题标题】:What am I doing wrong when inserting into a specific data structure?插入特定数据结构时我做错了什么?
【发布时间】:2018-03-25 01:34:24
【问题描述】:

我正在使用 SDL2 库来创建游戏。我将加载的 SDL_Textures 存储到此 ma​​p 容器中:

std::map<const SDL_Texture, std::vector<int[3]>> textures;

地图的SDL_Texture本身。 是一个x,y,z坐标的向量,代表所有渲染纹理的地方。

当我尝试将 std::pair 插入到结构中时,会出现问题,如下所示:

textures.insert(
    std::pair<const SDL_Texture, std::vector<int[3]>>( 
       SDL_CreateTextureFromSurface(renderer, s), 
       std::vector<int[3]>()
    )
);

其中 rendererSDL_RenderersSDL_SurfaceVisual Studio 2017 的 IDE 将其标记为不正确:

no instance of constructor "std::pair<_Ty1,_Ty2>::pair 
[with _ty1=const SDL_Texture, _Ty2=std::vector<int[3],std::allocator<int[3]>>]" 
matches the argument list argument types are: 
(SDL_Texture*, std::vector<int[3],std::allocator<int[3]>>)

它显然不知道如何构造 std::pair,但我不知道为什么,因为我能够在 for 循环中构造一个没有错误:

for (std::pair<const SDL_Texture, std::vector<int[3]>> tex : textures) {
}

我认为这与我作为插入的未初始化std::vector有关。是这个原因吗?如果是这样,是否有解决方法?如果不是,可能是什么问题?

另外,有没有更好的方法来做我想做的事情?我要追求速度。

【问题讨论】:

    标签: c++ insert containers sdl-2 stdmap


    【解决方案1】:

    看看SDL_CreateTextureFromSurface的声明:

    SDL_Texture* SDL_CreateTextureFromSurface(/* arguments omitted for brevity */)
    

    特别注意返回类型。这是SDL_Texture*。这意味着一个指向SDL_Texture的指针。

    接下来看一下地图的键类型:SDL_Texture。这与SDL_Texture* 不同。指针(通常)不能隐式转换为其指向的类型。


    您不应该复制SDL_Texture。最简单的解决方案是存储SDL_CreateTextureFromSurface返回的指针:

    std::map<SDL_Texture*, std::vector<int[3]>> textures;
    

    这将允许您稍后在不再需要纹理时使用 SDL_DestroyTexture 释放分配的资源。

    【讨论】:

    • 如何破坏贴图内的纹理?
    • @PlatinumFrog 通过将指针传递给SDL_DestroyTexture
    猜你喜欢
    • 1970-01-01
    • 2014-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多