const和非const键有什么区别? [英] What is difference between const and non const key?
问题描述
以下两行之间有什么区别?
map< int,float& map_data;
map< const int,float> map_data;
-
code> int 和
const int
是两种不同的类型。 - p>
std :: map< int,float>
和std :: map&
std :: map之间的区别< const int,float> ; 和
std :: map< int,float>
是一个程度,类似于之间的区别,例如 std :: map< int,float>
和 std :: map< std :: string,float>
在非 - const
,内部键类型 仍然是非< - code> const int
:
std :: map< const int,float> :: key_type => const int
std :: map< int,float> :: key_type => int
但是,映射键在语义上是不可变的,允许直接访问键(例如,取消引用迭代器,它产生 value_type
) const
ify 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>
因此,对于您而言,
虽然:标准正式要求 您的键类型是可复制和可移动的,和一些实施重用地图节点;在这些实现下,尝试使用 const
键将无法工作。
What is the difference between the following two lines?
map<int, float> map_data;
map<const int, float> map_data;
int
andconst int
are two distinct types.std::map<int, float>
andstd::map<const int, float>
are, similarly, different types.
The difference between std::map<const int, float>
and std::map<int, float>
is, to a degree, analogous to the difference between, say, std::map<int, float>
and std::map<std::string, float>
; you get a fresh map type for each.
In the non-const
case, the internal key type is still non-const
int
:
std::map<const int, float>::key_type => const int
std::map<int, float>::key_type => int
However, map keys are semantically immutable, and all map operations that allow direct access to keys (for example, dereferencing iterators, which yields value_type
) does const
ify 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>
So the difference may be largely invisible to you in every way that matters, if your implementation allows it.
That's not always the case, though: the standard officially requires your key type to be copyable and moveable, and some implementations re-use map nodes; under those implementations, attempting to use a const
key simply won't work.
这篇关于const和非const键有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!