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

查看:126
本文介绍了使用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;

但是当我尝试访问映射到苹果的值时,我得到一个垃圾值,而不是为什么它不像 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 string 。至少不是,如果我们将c字符串定义为一个字符数组,带有空终止符。键值类型是 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 默认使用 operator<(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"

数组,第三个是一个lvalue引用,它绑定到也是一个数组的字符串文字对象。作为单独的对象,他们的地址当然也不同。所以,如果你要写:

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] ,所以它们将由 operator [] 。关键值不同,即使每个数组包含相同的字符。

The output would be 0 for each, 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 characters.

解决方案:不要使用 operator< 将指针与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天全站免登陆