【发布时间】:2016-09-09 18:35:03
【问题描述】:
我在我的 C++ 程序中声明了一个像 map<char *, int> m 这样的哈希映射。但它不起作用,所以我按照Using char* as a key in std::map 的说明进行操作
并将我的地图声明为map<char *, int, cmp_str> m。我的程序看起来像这样
struct cmp_str
{
bool operator()(char const *a, char const *b)
{
return std::strcmp(a, b) < 0;
}
};
int main(int argc, char *argv[])
{
map<char *, int, cmp_str> m
//Reading strings from a file
while( not end of file )
{
// char *str contains the line
if(m.find(str) != m.end()) {m[str]++; }
else {m[str] = 1;}
}
}
当我执行程序时,如果找到所有字符串,但首先即使它们没有插入。当我尝试使用 map<string, int> m; 并将 char *str 转换为 std::string 时,它工作正常。但是输入文件太大了,我用string的时候需要很多时间。我不确定为什么当我使用char * 时它会找到所有字符串。任何帮助将不胜感激。
【问题讨论】:
-
那么你的问题是什么?
-
其实
std::map不是hash映射,而是二叉树。如果你想要一个哈希,你应该使用std::unordered_map。 -
发布MCVE。您发布的代码不完整。
-
这是不正确的重复
-
@JoachimPileborg
unordered_map<char *, int>没有帮助