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

    xiaoxiao2021-03-25  123

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

    转载请注明原文地址: https://ju.6miu.com/read-7310.html

    最新回复(0)