使用具有两个字段和一对字段的结构有什么区别?

发布于 2024-08-20 21:41:08 字数 39 浏览 8 评论 0原文

使用具有两个字段和一对字段的结构在内存分配和效率方面有什么区别?

What is the difference regarding memory allocation and efficiency between using a struct with two fields and a pair?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(6

爱*していゐ 2024-08-27 21:41:08

std::pair 提供预先编写的构造函数和比较运算符。这还允许它们存储在像 std::map 这样的容器中,而无需编写复制构造函数或通过 operator < 进行严格的弱排序(例如 std 所要求的) ::地图)。如果你不写它们,你就不会犯错误(还记得严格的弱排序是如何工作的吗?)所以使用 std::pair 更可靠。

std::pair provides pre-written constructors and comparison operators. This also allows them to be stored in containers like std::map without you needing to write, for example, the copy constructor or strict weak ordering via operator < (such as required by std::map). If you don't write them you can't make a mistake (remember how strict weak ordering works?) so it's more reliable just to use std::pair.

我的影子我的梦 2024-08-27 21:41:08

std::pair 带有许多构造函数和运算符。

struct 允许命名字段(firstsecond 除外),并且可以随时扩展。

如果可以的话,更喜欢使用struct。它可能会涉及一些开销,但绝对更容易维护。

std::pair comes with a number of constructors and operators.

A struct allow named fields (other than first and second) and is ready to be extended at any time.

Prefer a struct when you can. It may involve some overhead, but is definitely easier for maintenance.

青春有你 2024-08-27 21:41:08

就内存分配和效率而言,没有区别——因为这正是 std::pair 的本质。

In terms of memory allocation and efficiency, there is no difference -- since that's exactly what a std::pair is.

血之狂魔 2024-08-27 21:41:08

在内存分配或效率方面没有差异。事实上,在STL实现中我使用的pair被定义为structpair

No difference in terms of memory allocation or efficiency. In fact, in the STL implementation I am using pair is defined as struct pair

自由如风 2024-08-27 21:41:08

由于上面没有提到,如果您想要自己名称的好处,但想要 std::pair (或任何其他对象)的好处,您可以使用“using”(从 c++11 开始)。您可以在命名空间或类声明中设置它。

事实上,我的许多课程现在都是这样开始的……

using myPair = pair<int,string>;

参见。 C++ 参考。了解更多文档。

As this isn't mentioned above, if you want the benefits of your own name, but the advantages of std::pair (or any other objects), you can use "using" ( from c++11 onwards). You can set this in your namespace or class declaration.

In fact this is how many of my classes now start out...

using myPair = pair<int,string>;

cf. C++ reference. for more documentation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文