微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

 

原文地址:https://www.jb51.cc/wenti/3285991.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐