#include<iostream>
using namespace std;
#define x first
#define y second //宏定义,x为first,y为second
typedef int i; //重命名,i等同于int
struct Pair //结构体
{
int first,second;
};
struct Pair A; //变量A这个时候能够装两个int数据
pair<int,int> a; //变量a这个时候能够装两个int数据
//pair的作用是将两个数据和成一个数据,不仅限于int,可以包括很多数据类型,包括它自己,其本质也就是一个结构体。
typedef pair<int,pair<double,string>> P; //使用typedef重命名,简化代码
int main()
{
cin>>A.first>>A.second;
cin>>a.first>>a.second;
//由于我们已经用x,y替换了first,second
cout<<A.x<<A.y<<endl;
cout<<a.x<<a.y<<endl;
//pair也可以用初始化列表进行初始化
pair<int,int> b{1,2};
cout<<b.x<<b.y<<endl;
//更加复杂的pair形式(套娃)
pair< int , pair<double,string> > c { 1 , { 2.3 , "abc" } };
cout<<c.x<<' '<<c.y.x<<' '<<c.y.y<<endl;
//简化之后
P d { 2 , { 3.2 , "def" } };
cout<<d.x<<' '<<d.y.x<<' '<<d.y.y<<endl;
return 0;
}
记录一下pair的用法(简单易懂)
最新推荐文章于 2024-07-25 19:36:06 发布