std::map和 std::map之间有区别吗? 和 std::map?
据我了解, std::map 中值对中的键一旦插入就无法更改。 这是否意味着使用关键模板参数作为 const 创建映射没有效果?
std::map<int, int> map1;
std::map<const int, int> map2;
From what I understand, the key in a value pair in an std::map cannot be changed once inserted. Does this mean that creating a map with the key template argument as const has no effect?
std::map<int, int> map1;
std::map<const int, int> map2;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
std::map
无论如何都会配置其键类型:std::map::value_type
是std::pair;
。 如果将const
添加到键类型,const const int
将简单地折叠为const int
。std::map
constifies its key type anyway:std::map<int, int>::value_type
isstd::pair<const int, int>
. If you add aconst
to the key type,const const int
will simply collapse toconst int
.正如 Dewfy 所说,对于您给出的示例,这并不重要,因为 int 是内置类型,它将按值复制,但是对于 char* ,情况有点不同......
如果您有
那么您将无法插入声明为 const char* 的变量将失败,
并显示 a
实际上可以说,
您
您将被限制使用
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...
If you had
Then you can't insert a variable declared as const char* will fail
with a
you can actually say
with a
you'll be restricted to using
由于 int 是按值复制的,因此 const 声明没有任何意义。
另一方面
极大地改变了画面
since int is copied by value this declaration of const has no sense.
On other hand
dramatically changes a picture
你标题问题的答案是肯定的。 它们是有区别的。 您无法将
std::map
传递给采用std::map
的函数。然而,尽管地图的类型不同,但它们的功能行为是相同的。 这并不罕见。 在许多情况下,int 和 long 的行为相同,尽管它们在形式上是不同的类型。
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 astd::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.