Char*作为映射C++中的键
Char * as key in a map C++
我在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
,这是一种正确且更好的方式。
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 将函数类成员映射到类本身内部
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 使用std::函数映射对象方法
- 如何加载(或映射)文件部分的最大大小,但适合在Windows上的RAM
- C++映射分割错误(核心转储)
- 内联映射初始化的动态atexit析构函数崩溃
- 使用"std::unordereded_map"映射到"std::list"对象
- 如何从多映射中删除特定的重复项
- 在未初始化映射的情况下,将值插入到映射的映射中
- QT通过C++添加映射QML项目
- 在c++中访问int到类对象的映射时出错
- 在C++中搜索嵌套多映射值
- 错误处理.将系统错误代码映射到泛型
- C++匿名结构作为std::映射值
- 如何从存储在std::映射中的std::集中删除元素
- 递归无序映射
- 正在VS调试器中监视映射条目