c++ - 插入特定数据结构时我做错了什么?

标签 c++ insert containers sdl-2 stdmap

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

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]>()
    )
);

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 有关。是这个原因吗?如果是这样,是否有解决方法?如果不是,可能是哪里出了问题?

此外,是否有更好的方法来完成我想做的事情?我要追求速度。

最佳答案

看一下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/

相关文章:

php - 将二进制数据从 PHP 插入 MySQL 时为什么要使用 bin2hex?

c++ - std::scoped_allocator_adaptor 的目的是什么?

c++ - 为什么用户定义的转换没有在调用对象上隐式发生

c++ - Omnet++:作为复合模块的子模块调用时找不到类

iOS UITableViewController - 插入并滚动到底部 - 有时会跳跃

mysql - Codeigniter/mySQL 问题。在实际插入之前检查是否可以进行多次插入

docker - 我怎么知道 docker daemon 重启后哪个 docker 会重启

STL - c++0x 中的不可变设置键在哪里?

c++ - 复制构造函数是始终隐式定义,还是仅在使用时定义?

c++ - 编译器错误没有意义(错误是缺少函数参数)