c++ - std::map.count 使用 c 字符串不起作用?

标签 c++ string dictionary

我希望在性能情况下使用 C 字符串而不是 std::string。我有以下代码:

std::map<const char*, int> myMap;
.
.
.
myMap.insert(std::pair<const char*, int>(str.c_str(), myint));
std::cout << myMap.count(str.c_str()) << std::endl;

奇怪的是,我刚刚输入的值对于 count() 返回 0?

最佳答案

默认情况下,std::map使用 std::less比较键(这与 < 相同,真的,除了它保证也适用于不相关的指针)。这意味着它只是进行指针比较,绝对不是您想要的。

只需使用 C++11 字符串类型 ( std::string ) 而不是用于以 nul 结尾的字符串 ( const char* ) 的旧类型,就可以了。

关于c++ - std::map.count 使用 c 字符串不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24698121/

相关文章:

swift - 遍历字符串字典、自定义对象并调用自定义对象初始化程序

快速访问字典中的键返回 null

c++ - 加速 C++ 14-5 : Custom string class and reference counter works for one constructor but not another

c++ - 以类似方式处理 std::map<K,V> 和 std::map<K,V*>

c++ - std::复制失败, "cannot seek vector iterator after end"

python - 从字符串数组中替换 s 子字符串 - Python

c# - 无法从对象数组转换为字符串数组

c# - 使用区分文化的比较从字符串中获取子字符串

c++ - map 和比较类的 C++ 问题

C++ - Windows 上有类似 addr2line 的命令吗