我在C++程序中声明了像map<char *, int> m
这样的哈希映射。但它没有工作,所以我按照Using char* as a key in std::map 的指示,宣布我的地图像map<char *, int, cmp_str> m
。我的程序那种看起来像这样Char *作为地图中的键C++
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
时,它工作正常。但是输入文件非常大,当我使用字符串时需要很多时间。我不确定为什么它会在我使用char *
时发现所有字符串。任何帮助,将不胜感激。
那么你的问题是什么? –
其实['std :: map'](http://en.cppreference.com/w/cpp/container/map)不是* hash *映射,它是一个二叉树。如果你想要一个散列,你应该使用['std :: unordered_map'](http://en.cppreference.com/w/cpp/container/unordered_map)。 –
发布[MCVE](http://stackoverflow.com/help/mcve)。您发布的代码不是*完整*。 –