简体   繁体   English

std :: map之间有区别吗? <int, int> 和std :: map <const int, int> ?

[英]Is there a difference between std::map<int, int> and std::map<const int, int>?

From what I understand, the key in a value pair in an std::map cannot be changed once inserted. 据我所知,std :: map中值对中的键在插入后无法更改。 Does this mean that creating a map with the key template argument as const has no effect? 这是否意味着使用键模板参数创建一个映射为const无效?

std::map<int, int> map1;
std::map<const int, int> map2;

The answer to your title question is yes. 标题问题的答案是肯定的。 There is a difference. 它们是有区别的。 You cannot pass a std::map<int, int> to a function that takes a std::map<const int, int> . 您不能将std::map<int, int>传递给采用std::map<const int, int>

However, the functional behavior of the maps is identical, even though they're different types. 但是,地图的功能行为是相同的,即使它们是不同的类型。 This is not unusual. 这并不罕见。 In many contexts, int and long behave the same, even though they're formally different types. 在许多情况下,int和long表现相同,即使它们是正式的不同类型。

since int is copied by value this declaration of const has no sense. 因为int是按值复制的,所以这个const的声明没有任何意义。 On other hand 在另一方面

std::map<const char*, int> map2; 

dramatically changes a picture 大幅改变画面

std::map constifies its key type anyway: std::map<int, int>::value_type is std::pair<const int, int> . std::map无论如何都要构造它的键类型: std::map<int, int>::value_typestd::pair<const int, int> If you add a const to the key type, const const int will simply collapse to const int . 如果向键类型添加const ,则const const int将简单地折叠为const int

As Dewfy said, with the example you gave, it doesn't matter since int is a built in type and it will be copied by value, but with char* it's a little different... 正如Dewfy所说,用你给出的例子,没关系,因为int是一个内置类型,它将被值复制,但是有了char *,它有点不同......

If you had 如果你有

std::map<char *, int> map;

Then you can't insert a variable declared as const char* will fail 然后你不能插入声明为const char *的变量将失败

char * y = new char[4];
const char * x = "asdf";
std::map<char *, int> map;
map.insert(make_pair(y, 4)); //ok
map.insert(make_pair(x, 4)); //fail

with a 用一个

std::map<char*, int> map;

you can actually say 你实际上可以说

char * x = new char[1];
(*x) = 'a';
map<char*,int>::iterator it = map.begin();
cout<<it->first; //prints 'a'
(it->first)[0] = 'x'
cout<<it->first; //prints 'x'

with a 用一个

 std::map<const char *, int>

you'll be restricted to using 你将被限制使用

 map<const char*, int>::iterator 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM