以指针为键的映射的 value_type
据我所知,C++ 将 map::value_type
定义为 pair
如果我使用指针类型作为键类型会发生什么在地图中,即,正如
std::map<const char*,int>::value_type::first_type = const char*
我从上面的定义中所期望的那样,或者
std::map<const char*,int>::value_type::first_type = const char* const
更符合逻辑(因为否则我将被允许从地图迭代器更改键值)?
For what I know, C++ defines map<a,b>::value_type
as pair<const a,b>
What will happen if I use a pointer type as key type in map, i.e., is
std::map<const char*,int>::value_type::first_type = const char*
as I would expect from definition above or
std::map<const char*,int>::value_type::first_type = const char* const
as would be more logical (since otherwise i would be allowed to change key value from a map iterator)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的推理是正确的,
value_type::first
将是char const * const
。有一个常见的混淆来源,即当
T
是type *
时,认为const T
是const type *
,但事实并非如此。与宏不同,typedef
不是文本替换,模板参数也不是。当您执行const T
时,如果T
是typedef
或模板参数,您将向键入一个整体。这就是为什么我喜欢在类型右侧编写
const
的原因之一,因为它会减少混乱:T const *
,添加一个额外的 const,得到T const * const
。Your reasoning is correct,
value_type::first
would bechar const * const
.There is a common source of confusion in thinking that
const T
whenT
is atype *
isconst type *
, but that is not so. Unlike macros,typedef
s are not text substitution, nor are template arguments. When you doconst T
, ifT
is atypedef
or template argument, you are adding aconst
to the type as a whole.That is the one reason why I like to write my
const
s at the right of the type, as it causes less confusion:T const *
, add an extra const, getT const * const
.如果
a
是const char*
,那么const a
确实是const char* const
。If
a
isconst char*
, thenconst a
is indeedconst char* const
.您的评估是正确的,但您必须非常小心这种方法,原因有两个:
You are correct in your assessment, but you have to be very careful with this approach for two reasons: