具有 2 个单元格的结构与 std::pair 相比?

2021-12-23 00:00:00 struct c++ std-pair

可能的重复:
有什么区别在使用具有两个字段和一对的结构之间?

亲爱的,

我有一个关于pairs和struct的小问题.使用 std::pair 而不是具有两个单元格的结构有什么好处吗?我已经使用了一段时间,但主要问题是可读性:如果你想表示例如一个双重(int "label", double "value"),你可以使用 a :

I have a little question about pairs and struct. Is there any advantage to use a std::pair instead of a struct with two cells ? I have used pairs for a while but the main problem is readability : If you want to represent for example a duple (int "label", double "value") you can use either a :

typedef std::pair<int,double> myElem;

typedef struct {
    int label;
    double value;
} myElem;

如果您的语句具有语义"意义(您将始终知道 x.label 是什么.x.first 不是这种情况),则代码会变得更具可读性.

The code becomes more readable if your statements have a "semantic" sense (you will always know what x.label is. that's not the case with x.first).

但是,我想使用 pair 是有优势的.是性能更好还是其他什么?

However, I guess there is an advantage using pair. Is it more performant or something else?

推荐答案

pair 被实现为模板化的 struct.它为您提供了创建(通常是异类)对的简写.此外,对于可以与 pair 一起使用的类型有一些限制:

A pair is implemented as a templated struct. It provides you with a shorthand for creating a (typically heterogenous) pair. Also, there are some constraints on the types that you can use with a pair:

类型要求

T1 和 T2 都必须成为可分配的模型.额外的操作有额外的要求.配对的默认值构造函数只能在两者都使用时使用T1 和 T2 是 DefaultConstructible,operator== 只能在两个 T1 时使用和 T2 是 EqualityComparable,并且运算符<只能在两个 T1 时使用和 T2 是 LessThanComparable.

T1 and T2 must both be models of Assignable. Additional operations have additional requirements. Pair's default constructor may only be used if both T1 and T2 are DefaultConstructible, operator== may only be used if both T1 and T2 are EqualityComparable, and operator< may only be used if both T1 and T2 are LessThanComparable.

(来自 SGI STL std::pair 文档)

(from SGI STL std::pair documentation)

如果类型不遵循任何这些约束或者您不关心它们,那么定义您自己的 POD 可能是有意义的.

Defining your own POD may make sense if the types do not follow any of these constraints or if you do not care about them.

最后,我想这是个人选择/编码风格的问题.

Finally, I guess it is a matter of personal choice/coding style.

相关文章