C++ pair

1. pair 简介

1.1 功能

//类模板:
template<class _T1, class _T2> struct pair
{
	typedef _T1 first_type;
	typedef _T2 second_type;
	_T1 first;
	_T2 second;
	
	pair(): first(), second()
	 { }
	 
	pair(const _T1& __a, const _T2& __b)
	: first(__a), second(__b) 
	{ }
	
	template<class _U1, class _U2>pair(const pair<_U1, _U2>& __p)
	: first(__p.first), second(__p.second) 
	{ }
};

模板参数:T1是第一个值的数据类型,T2是第二个值的数据类型。 这一对值可以具有不同的数据类型(T1和T2),两个值可以分别用pair的两个公有函数firstsecond访问。

2. pair 的使用场景举例

  • map/multimap 类 中存放的就是pair 对象。
  • 当一个函数需要返回两个数据时可以使用pair。

3. pair 的使用

3.1 创建pair

pair<int, string> student;        // 创建一个空对象student,第一个元素为int类型 第二哥元素为string类型
pair<string, vector<int> > line;  // 创建一个空对象line,两个元素类型分别是string和vector类型

3.2 创建时初始化

pair<string, string> author("James","Joy");    // 创建一个author对象,两个元素类型分别为string类型,并默认初始值为James和Joy。
pair<string, int> name_age("Tom", 18);
pair<string, int> name_age2(name_age);    // 拷贝构造初始化

3.3 pair类对象间赋值

pair<int, double> p1(1, 1.2);
pair<int, double> p2 = p1;     // copy construction to initialize object
pair<int, double> p3;
p3 = p1;    // operator =

3.4 使用make_pair 函数生成pair

pair<int, double> p1;
p1 = make_pair(1, 1.2);
cout << p1.first << p1.second << endl;
 //output: 1 1.2
int a = 8; 
string m = "James";
pair<int, string> newone;
newone = make_pair(a, m);
cout << newone.first << newone.second << endl;
//output: 8 James

pair 模板类对象中有一个 模板构造函数,具有自动推断 make_pair 的参数类型的功能。

3.5 操作pair

pair<int ,double> p1;
p1.first = 1;
p1.second = 2.5;
cout<<p1.first<<' '<<p1.second<<endl;
//输出结果:1 2.5
string firstBook;
if(author.first=="James" && author.second=="Joy")
    firstBook="Stephen Hero";
原文地址:https://www.cnblogs.com/lasnitch/p/12764117.html