char*做map的key使用时的问题

来源:互联网 发布:福建广电网络集团 网址 编辑:程序博客网 时间:2024/06/04 23:24

        今天在工作中使用到map时,map中用char*字符串做key,后面通过key做find操作,发现找不到之前插入的元素。通过网上搜索,得出结论,find时,默认使用== 进行判断,char*只是指针,如果两个字符串值相同,但是地址不同,是无法匹配的。

        所以最好使用std::string。如果非要用char*,需要使用find_if函数并且用bind2sd函数指定比较函数。

#include <map>#include <algorithm>#include <iostream> using namespace std; bool search(pair<char*, int> a, const char* b){    return strcmp(a.first, b) == 0 ? true : false;}int main(){    map<char*, int> test;    test.insert(pair<char*, int>("abc", 1));     map<char*, int>::const_iterator iter = find_if(test.begin(), test.end(),  bind2nd(ptr_fun(search), "abc"));     if (iter != test.end())    {        cout<< "find : " << iter->first << endl;    }     return 0;}

0 0
原创粉丝点击