What is the difference between using a struct with two fields and a pair?

匆匆过客 提交于 2019-11-27 21:05:14
AshleysBrain

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.

Matthieu M.

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.

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

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

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!