C++ pair的用法实例详解(结构体模板应用初探)

1 pair的应用(结构体模板)

pair是将2个数据组合成一个数据,当需要这样的需求时就可以使用pair,如stl中的map就是将key和value放在一起来保存。另一个应用是,当一个函数需要返回2个数据的时候,可以选择pair。

头文件:#include<utility>

类模板:template <class T1, class T2> struct pair

定义方法:

    pair<变量类型1,变量类型2> 变量名

eg:  pair<int,int>p;

.实例化

eg:pair<int,int>(3,4)//初始化一个pair,第一个成员是int,第二个成员也是int类型

对象的赋值以及make_pair()的应用:

 pair<int,int> q = make_pair(3 ,4);

(1)第一种用法函数返回:        

pair<int,int> func()
{
   int height = 3;
   int weight = 4;
   return pair<int,int>(3,4);
}

int main(int argc, char *argv[])
{
 
    pair<int, int> p = func(); //调用函数
 
    return 0;
}
 

cout<<p.first<<" "<<p.second<<endl; //

(2)使用在stl map

struct student {
    int height;
    int weight;
};
 
 
 
int main(int argc, char *argv[])
{
    map<int ,struct student> map1;
    struct student a;
    struct student b;
    //错误写法 map.insert<1,a>;错误写法
 
    map1.insert(pair<int, struct student>(1, a));//等价于 ----- map1.insert(make_pair(1, a));
    cout<<map1.size()<<endl;
 
 
 
    return 0;
}
 

3.pair中元素的访问(first & second):

    eg:

pair<int,int> func()
{
   int height = 3;
   int weight = 4;
   return pair<int,int>(3,4);
}
  pair<int, int> p = func();
    cout<<p.first<<" "<<p.second<<endl;


说到这里,有的同学应该想问,这不就是c语言的结构体吗?是的,这就是c++的结构体模板

源码:

template<class _T1, class _T2>
    struct pair
    {
      typedef _T1 first_type;    /// @c first_type is the first bound type
      typedef _T2 second_type;   /// @c second_type is the second bound type
 
      _T1 first;                 /// @c first is a copy of the first object
      _T2 second;                /// @c second is a copy of the second object、
....
    .......

对了什么叫结构体模板,哈哈,敬请关注!!!





  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值