Char*作为映射C++中的键

Char * as key in a map C++

本文关键字:C++ 映射 Char      更新时间:2023-10-16

我在C++程序中声明了一个类似map<char *, int> m的哈希映射。但它不起作用,所以我遵循了在std::map中使用char*作为键的说明并像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;}
  }
}

当我执行程序时,if会先找到所有字符串,即使它们没有插入。当我尝试使用map<string, int> m;并将char *str转换为std::string时,它运行良好。但是输入文件太大了,当我使用字符串时会花费很多时间。我不知道为什么当我使用char *时它会找到所有字符串。如有任何帮助,我们将不胜感激。

当您使用map<char *, int, cmp_str> m时,在将缓冲区插入std::map后,您无法修改该缓冲区,因为映射不复制数据,而是复制指针本身。当你使用std::map<std::string,int>时,std::string确实会复制,这就是为什么它能工作,而且速度较慢。因此,您要么需要手动创建许多缓冲区并在其中存储字符串(这会使程序速度变慢),要么使用std::string,这是一种正确且更好的方式。