const 键和非 const 键有什么区别?

2024-03-28

下面两行有什么区别?

map<int, float> map_data;
map<const int, float> map_data;

  • int and const int是两种不同的类型。

  • std::map<int, float> and std::map<const int, float>同样,它们是不同的类型。

和...之间的不同std::map<const int, float> and std::map<int, float>在某种程度上,类似于以下之间的区别:std::map<int, float> and std::map<std::string, float>; 每个你都会得到一个新的地图类型。

在非constcase,内部密钥类型is仍然非const int:

std::map<const int, float>::key_type       => const int
std::map<int, float>::key_type             => int

然而,地图键是语义上不可变的,以及允许直接访问键的所有映射操作(例如,取消引用迭代器,这会产生value_type) does constify the key_type:

std::map<const int, float>::value_type => std::pair<const int, float>
std::map<int, float>::value_type       => std::pair<const int, float>

所以区别may如果您的实施允许的话,在所有重要的方面对您来说基本上都是不可见的。

但情况并非总是如此:官方标准requires您的密钥类型可复制和可移动,并且一些实现重用地图节点 http://lists.cs.uiuc.edu/pipermail/cfe-dev/2011-July/015926.html;在这些实现下,尝试使用const钥匙根本不起作用。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

const 键和非 const 键有什么区别? 的相关文章

随机推荐