struct with 2 cells vs std :: pair? [英] struct with 2 cells vs std::pair?

查看:148
本文介绍了struct with 2 cells vs std :: pair?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

尊敬的:

我有一个关于对和结构的问题。使用std :: pair而不是两个单元格的结构有什么优势吗?
我已经使用了一段时间,但主要的问题是可读性:
如果你想表示一个duple(intlabel,双value),你可以使用一个:

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;

如果语句具有语义意义,代码变得更加可读.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).

但是,我想使用对有一个优势。

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

推荐答案

实现了作为模板 struct 。它为您提供了创建(通常是异构的)对的速记。此外,对于对可以使用的类型有一些约束:

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必须同时为
才能作为可分配的模型。额外的
操作有额外的
需求。 Pair的默认
构造函数只能在
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.

这篇关于struct with 2 cells vs std :: pair?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆