c++ - const 和非 const 键有什么区别?

标签 c++ key language-lawyer key-value stdmap

下面两行有什么区别?

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

最佳答案

  • intconst int是两种不同的类型。

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

std::map<const int, float> 的区别和 std::map<int, float>在某种程度上,类似于 std::map<int, float> 之间的差异。和 std::map<std::string, float> ; 您会为每个 map 类型获得新的 map 类型。

在非const在这种情况下,内部 key 类型仍然非const int :

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

但是,映射键在语义上是不可变的,并且所有允许直接访问键的映射操作(例如,解引用迭代器,它会产生 value_type )都可以 const确定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>

因此,如果您的实现允许,差异可能在很大程度上对您来说是不可见的。

但情况并非总是如此:标准正式要求您的 key 类型是可复制和可移动的,some implementations re-use map nodes ;在这些实现下,尝试使用 const键根本不起作用。

关于c++ - const 和非 const 键有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17638154/

相关文章:

java - HashMap 对象键

mysql - Mysql Workbench错误1452-无法创建源表

c++ - 直接初始化中的转换运算符

c++ - 使用默认参数为模板函数起别名

c++ - 在 C++、OpenGL 中使用 De Casteljau 算法绘制贝塞尔曲线

java - 如何打包java项目?

实现是否可以将提示视为实际语句?

c - 关于在 printf 函数中使用时指向整数的未初始化指针的行为问题

c++ - 基于模板参数的C++模板添加/启用构造函数

c++ - 什么是 T (& var)[N]?