Pair c++

Pair

  1. 应用
    1. 将2个数据组合成一组数据
    2. 当函数需要返回2个数据的时候
  2. pair的实现是一个结构体,主要的两个成员变量是first, second
  3. #include
  4. 定义
pair<T1, T2> p1;  //T1 T2两个数据类型
pair<T1, T2> p1(v1, v2);
p1 = make_pair(v1, v2);  //创建新的pair对象

// 使用typedef简化声明
typedef pair<int,string> P;
P a[N];

//赋值
pair<int, int> p1(1, 2);
pair<int, int> p2 = p1; 
  1. 操作
//访问
cout<<p1.first<<' '<<p1.second<<endl;
  1. 函数返回
#include <iostream>

using namespace std;

typedef  pair<int,int> P;

P fun(){
    P p1(1,2);
    return p1;
}

int main(){
    P p2;
    p2 = fun();
    cout<<p2.first<<p2.second<<endl;

    int a;
    int b;
    tie(a,b) = p2;  // tie c++11 新特性
    cout<<a<<b<<endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/wendiudiu/p/10784690.html