使用具有两个字段和一对字段的结构有什么区别?
使用具有两个字段和一对字段的结构在内存分配和效率方面有什么区别?
What is the difference regarding memory allocation and efficiency between using a struct with two fields and a pair?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
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 viaoperator <
(such as required bystd::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 usestd::pair
.std::pair
带有许多构造函数和运算符。struct
允许命名字段(first
和second
除外),并且可以随时扩展。如果可以的话,更喜欢使用
struct
。它可能会涉及一些开销,但绝对更容易维护。std::pair
comes with a number of constructors and operators.A
struct
allow named fields (other thanfirst
andsecond
) 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.就内存分配和效率而言,没有区别——因为这正是
std::pair
的本质。In terms of memory allocation and efficiency, there is no difference -- since that's exactly what a
std::pair
is.在内存分配或效率方面没有差异。事实上,在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
由于上面没有提到,如果您想要自己名称的好处,但想要 std::pair (或任何其他对象)的好处,您可以使用“using”(从 c++11 开始)。您可以在命名空间或类声明中设置它。
事实上,我的许多课程现在都是这样开始的……
参见。 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...
cf. C++ reference. for more documentation.
如 std::pair中所述与具有两个 int 的 struct 相比,一个 struct 可能会快一点,因为没有进行初始化。
As stated in std::pair<int, int> vs struct with two int's a struct will probably be a little bit faster because no initialization is made.