c++ 模板类 pair

 pair类的头文件

#include <utility>

pair类

pair类是一个模板类

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

template<class T1,class T2> struct pair

如何访问pair类中的两个元素

pair->first()

pair->(second)

构造函数

认构造函数,即创建空的 pair 对象

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);
}

 

相关文章

显卡天梯图2024最新版,显卡是电脑进行图形处理的重要设备,...
初始化电脑时出现问题怎么办,可以使用win系统的安装介质,连...
todesk远程开机怎么设置,两台电脑要在同一局域网内,然后需...
油猴谷歌插件怎么安装,可以通过谷歌应用商店进行安装,需要...
虚拟内存这个名词想必很多人都听说过,我们在使用电脑的时候...
win11本地账户怎么改名?win11很多操作都变了样,用户如果想要...