以指针为键的映射的 value_type

发布于 2024-12-10 12:01:04 字数 398 浏览 0 评论 0原文

据我所知,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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

落叶缤纷 2024-12-17 12:01:04

您的推理是正确的,value_type::first 将是char const * const

有一个常见的混淆来源,即当 Ttype * 时,认为 const Tconst type * ,但事实并非如此。与宏不同,typedef 不是文本替换,模板参数也不是。当您执行 const T 时,如果 Ttypedef 或模板参数,您将向键入一个整体。

这就是为什么我喜欢在类型右侧编写 const 的原因之一,因为它会减少混乱:T const *,添加一个额外的 const,得到T const * const

Your reasoning is correct, value_type::first would be char const * const.

There is a common source of confusion in thinking that const T when T is a type * is const type *, but that is not so. Unlike macros, typedefs are not text substitution, nor are template arguments. When you do const T, if T is a typedef or template argument, you are adding a const to the type as a whole.

That is the one reason why I like to write my consts at the right of the type, as it causes less confusion: T const *, add an extra const, get T const * const.

嘿哥们儿 2024-12-17 12:01:04

如果aconst char*,那么const a确实是const char* const

If a is const char*, then const a is indeed const char* const.

美人骨 2024-12-17 12:01:04

您的评估是正确的,但您必须非常小心这种方法,原因有两个:

  1. 您必须提供一个自定义比较器谓词,该比较器谓词对 const char * 进行正确排序(例如,使用 strcmp 的变体,仅在以下情况下返回 true键 1 < 键 2 )。如果您不这样做,您的字符串将按指针值排序,这几乎总是不是您想要的。
  2. 您必须考虑地图中键的生命周期以及当地图被破坏时它们将如何被释放。

You are correct in your assessment, but you have to be very careful with this approach for two reasons:

  1. You have to supply a custom comparator predicate that does proper ordering of const char * (e.g., using a variant of strcmp that only returns true if key1 < key2 ). If you do not do this, your strings will be ordered by pointer values, which is almost always not what you want.
  2. You have to consider the lifetime of the keys in your map and how they will be deallocated when the map is destroyed.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文