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

        今天在工作中使用到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;
}


版权声明:本文为xijiacun原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。