STL map<char*,void*> 的find问题

来源:互联网 发布:层次数据库 编辑:程序博客网 时间:2024/06/07 17:27

map<char*,void*> _map;void* ptr;_map[filename] = ptr;load_resource(char* filename){std::string s(filename);char* t = (char*)s.c_str();                //直接find(filename)和find(t)的结果不一样,一个找得到,一个找不到map::iterator it = _map.find(t);        if(_map.end() != it){    //find}        else        {            //not find        }        //code}
问题见代码注释。求解,谢谢。
但是为啥这个代码运行正常?
load_resource(char* filename){map::iterator it = _map.find(filename);        if(_map.end() != it){    //find}        else        {              _map[filename] = ptr;            //not find        }        //code}load_resource("aaa");//这次调用not find,于是使用这个key创建了这个项目load_resource("aaa");//这次调用find

答案:

因为当你用char*当key的时候,key实际上是那个指针的值,所以你用string来一下当然是要失败。如果你要用char*的内容当key的话,你必须写成map<string, void*>。

0 0
原创粉丝点击