pair类的头文件
#include <utility>
pair类
pair类是一个模板类
std::pair主要的作用是将两个数据组合成一个数据,两个数据可以是同一类型或者不同类型。
template<class T1,class T2> struct pair
如何访问pair类中的两个元素
pair->first()
pair->(second)
构造函数
pair();
直接使用 2 个元素初始化成 pair 对象
pair (const first_type& a, const second_type& b);
拷贝(复制)构造函数,即借助另一个 pair 对象,创建新的 pair 对象
template<class U, class V> pair (const pair<U,V>& pr);
移动构造函数
template<class U, class V> pair (pair<U,V>&& pr);
使用右值引用参数,创建 pair 对象
template<class U, class V> pair (U&& a, V&& b);
make_pair()
代码
#include <iostream>
#include <string>
#include <utility>
using namespace std;
int main()
{
pair<string,string> p1; //默认构造函数
pair<string,string> p2("p1","(int,double)");
pair<string,string> p3(p2);//拷贝构造函数
pair<string,string> p4(make_pair("p2","(string,string)"));//移动构造函数
auto print = [](pair<string,string> &a){
cout<<a.first<<" "<<a.second<<endl;
};
cout<<"p1"<<endl;
print(p1);
cout<<"p2"<<endl;
print(p2);
cout<<"p3"<<endl;
print(p3);
cout<<"p4"<<endl;
print(p4);
}