下面两行有什么区别?
map<int, float> map_data;
map<const int, float> map_data;
最佳答案
int
和const 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/