将SDL曲面与文件名一起放在地图中

我很擅长在C ++中使用地图,所以我在使用SDL表面时遇到了一些困难。这是我尝试过的(不工作):
map <SDL_Surface*, char*> mSurfaceMap;

mSurfaceMap.insert(pair<SDL_Surface*, char*>(m_poSurfaceTest, "..//..//gfx//testImage.png"));
我们的想法是将所有曲面及其相应的图像文件放在地图中,以便轻松初始化它们并对它们进行
IMG_Load()
,并在关闭程序时释放它们。 如果这是一个不好的解决方案,请指出我正确的方向。我首先考虑制作两个阵列,但我想尝试这个,因为我觉得这是一个更优雅的解决方案。如果解决方案没问题,我很想听听我在代码中做错了什么。     
已邀请:
这段代码适合我。输出符合预期:
#include <map>
#include <stdio.h>

using std::map;
using std::pair;

struct Custom
{
    int val;
    Custom() {val=0;}
};

int main(int argC,char* argV[]) 
{
    map<Custom*,char*> mMap;
    Custom* test = new Custom;
    mMap.insert(pair<Custom*,char*>(test,"Test"));
    printf("%sn",mMap[test]);
    return 0;
}
    
std::map
非常适合按有序键查找数据,它通常实现为平衡二叉树,可提供O(log n)查找时间。如果查找顺序无关紧要,则
std::hash_map
将是O(1)查找时间的更好选择。 在任一容器中使用指针作为键的问题在于它们将通过指针的整数地址进行索引,而不是指向的值。 但是,
std::string
具有值语义并实现了less-than操作符,它将使容器索引字符串的值。 您可能还希望将表面放在智能指针中以进行内存管理。
typedef std::tr1::shared_ptr<SDL_Surface> surface_pointer;
typedef pair<std::string, surface_pointer > surface_pair;

std::map<std::string, surface_pointer > mSurfaceMap;

mSurfaceMap.insert(surface_pair("..//..//gfx//testImage.png", surface_pointer(m_poSurfaceTest)));
其他一些想法...... 如果您不需要查找功能,并且只是使用容器进行内务管理,那么简单的
std::vector<std::pair<std::string, SDL_Surface*> >
可能就足以满足您的需求。 或者,如果您已将曲面存储为成员(假设来自变量名称),则可以将成员变量存储为
tr1::unique_ptr<SDL_Surface>
,并且当删除包含类时,将删除
SDL_Surface
。为了使这个工作,你需要为
tr1::unique_ptr
提供一个自定义解除分配器,它将教它如何释放
SDL_Surface*
struct SdlSurfaceDeleter {
    void operator() (SDL_Surface*& surface) {
        if (surface) {
            SDL_FreeSurface(surface);
            surface = NULL;
        }
    }
};
然后你会像这样指定你的成员(typedef使它更简洁):
typedef std::tr1::unique_ptr<SDL_Surface, SdlSurfaceDeleter> surface_ptr;

class MyClass {
public:
    MyClass(const std::string& path)
        : m_poSurfaceTest(IMG_Load(path.c_str()) { }

    surface_ptr m_poSurfaceTest;
};
    

要回复问题请先登录注册