我正在使用 SDL2 库创建游戏。我将加载的 SDL_Textures 存储到这个 map 容器中:
std::map<const SDL_Texture, std::vector<int[3]>> textures;
map 的键是SDL_Texture本身。 value 是一个包含x,y,z 坐标的 vector ,代表渲染纹理的所有位置。
当我尝试将 std::pair 插入到结构中时,我遇到了这个问题,如下所示:
textures.insert(
std::pair<const SDL_Texture, std::vector<int[3]>>(
SDL_CreateTextureFromSurface(renderer, s),
std::vector<int[3]>()
)
);
renderer 是 SDL_Renderer,s 是 SDL_Surface。 Visual 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 有关。是这个原因吗?如果是这样,是否有解决方法?如果不是,可能是哪里出了问题?
此外,是否有更好的方法来完成我想做的事情?我要追求速度。
最佳答案
看一下SDL_CreateTextureFromSurface
的声明:
SDL_Texture* SDL_CreateTextureFromSurface(/* arguments omitted for brevity */)
请特别注意返回类型。它是 SDL_Texture*
。这意味着 指向 SDL_Texture
的指针。
接下来查看 map 的关键类型:SDL_Texture
。这与 SDL_Texture*
不同。指针(通常)不能隐式转换为其指向的类型。
您不应该复制 SDL_Texture
。最简单的解决方案是存储 SDL_CreateTextureFromSurface
返回的指针:
std::map<SDL_Texture*, std::vector<int[3]>> textures;
这将允许您稍后在不再需要使用 SDL_DestroyTexture
的纹理时释放分配的资源。
关于c++ - 插入特定数据结构时我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49471690/