C++常见用法——pair和make_pair

一、相同点

pair和make_pair的主要作用都是将两个数据组合成一个数据,两个数据可以是同一个类型或者不同类型。

二、区别
  • pair实际上是一个结构体,其主要的两个成员变量是first和second,这两个变量可以直接使用。
伪代码如下:
first = pair.first
second= pair.second
  • 一般make_pair都使用在需要pair做参数的位置,可以直接调用make_pair生成pair对象
伪代码如下:
pair <string,double> product3;
product3 = make_pair ("shoes",20.0);
三、 pair和make_pair应用实例
#include <iostream>
#include <utility>
#include <string>
using namespace std;

int main () {
	pair <string,double> product1 ("tomatoes",3.25);
    pair <string,double> product2;
    pair <string,double> product3;

    product2.first = "lightbulbs";     // type of first is string
    product2.second = 0.99;            // type of second is double
 
    product3 = make_pair ("shoes",20.0);
 
    cout << "The price of " << product1.first << " is $" << product1.second << "\n";
    cout << "The price of " << product2.first << " is $" << product2.second << "\n";
    cout << "The price of " << product3.first << " is $" << product3.second << "\n";
    return 0;
 }
四、pair和make_pair定义
// TEMPLATE STRUCT pair
 template<class _Ty1,class _Ty2> struct pair
 {   // store a pair of values
 	typedef pair<_Ty1, _Ty2> _Myt;
    typedef _Ty1 first_type;
    typedef _Ty2 second_type;
 
    pair(): first(_Ty1()), second(_Ty2()){    
    	// construct from defaults
    	} 
    pair(const _Ty1& _Val1, const _Ty2& _Val2): first(_Val1), second(_Val2){    
    // construct from specified values
    	}
 
    template<class _Other1,
    class _Other2>
    pair(const pair<_Other1, _Other2>& _Right)
    : first(_Right.first), second(_Right.second){    
    	// construct from compatible pair
    	}
 
    void swap(_Myt& _Right){    
    	// exchange contents with _Right
        std::swap(first, _Right.first);
        std::swap(second, _Right.second);
        }
 
 	_Ty1 first;    // the first stored value
    _Ty2 second;    // the second stored value
    	};
 

template<class _Ty1,class _Ty2> inline
	pair<_Ty1, _Ty2> make_pair(_Ty1 _Val1, _Ty2 _Val2){    
		// return pair composed from arguments
    return (pair<_Ty1, _Ty2>(_Val1, _Val2));
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值