使用C ++ STL将C样式字符串映射到int? [英] Map C-style string to int using C++ STL?

查看:112
本文介绍了使用C ++ STL将C样式字符串映射到int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

string 映射到 int 工作正常。

std::map<std::string, int> // working

但我想映射 C风格 string to int

But I want to map C-style string to int

例如:

char A[10] = "apple";
map<char*,int> mapp;
mapp[A] = 10;

但是当我尝试访问映射到apple的值时, 10.为什么它的行为不像 std :: string

But when I try to access the value mapped to "apple" I am getting a garbage value instead of 10. Why it doesn't behave the same as std::string?

推荐答案


map<char*,int> mapp;


。至少不是,如果我们将c字符串定义为一个字符数组,带有null终结符。键类型,即 char * 是指向字符对象的指针。区分是重要的。您不是在地图中存储字符串。

They key type here is not "c string". At least not, if we define c string to be "an array of characters, with null terminator". The key type, which is char*, is a pointer to a character object. The distinction is important. You aren't storing strings in the map. You are storing pointers, and the strings live elsewhere.

除非使用自定义比较函数对象,否则 std :: map 默认使用运算符<(const key_type&,key_type&)

Unless you use a custom comparison function object, std::map uses operator<(const key_type&,key_type&) by default. Two pointers are equal if, and only if they point to the same object.

这里是三个对象的示例:

Here is an example of three objects:

char A[] = "apple";
char B[] = "apple";
const char (&C)[6] = "apple"

数组,第三个是绑定到也是数组的字符串文字对象的左值引用。作为单独的对象,它们的地址当然也不同。那么,如果你写:

First two are arrays, the third is an lvalue reference that is bound to a string literal object that is also an array. Being separate objects, their address is of course also different. So, if you were to write:

mapp[A] = 10;
std::cout << mapp[B];
std::cout << mapp[C];

输出将为0,因为您尚未初始化 mapp [B ] 也不是 mapp [C] ,因此它们将被

The output would be 0, because you hadn't initialized mapp[B] nor mapp[C], so they will be value initialized by operator[]. The key values are different, even though each array contains the same c string.

解决方案:不要使用运算符< 将指针与c字符串进行比较。请改用 std :: strcmp 。使用 std :: map ,这意味着使用自定义比较对象。但是,你还没有完成注意事项。您还必须确保字符串必须保留在内存中,只要它们由地图中的键指向即可。例如,这将是一个错误:

Solution: Don't use operator< to compare pointers to c strings. Use std::strcmp instead. With std::map, this means using a custom comparison object. However, you aren't done with caveats yet. You must still make sure that the strings must stay in memory as long as they are pointed to by the keys in the map. For example, this would be a mistake:

char A[] = "apple";
mapp[A] = 10;
return mapp; // oops, we returned mapp outside of the scope
             // but it contains a pointer to the string that
             // is no longer valid outside of this scope

解决方案:照顾范围,或者使用 std :: string

Solution: Take care of scope, or just use std::string.

这篇关于使用C ++ STL将C样式字符串映射到int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆