c++ 中pair类模板的用法详解

来源:互联网 发布:化合物谱图数据库查询 编辑:程序博客网 时间:2024/06/04 00:27

pair:

头文件:#include<utility>

类模板:template <class T1, class T2> struct pair

参数:T1是第一个值的数据类型,T2是第二个值的数据类型。

功能:pair将一对值组合成一个值,这一对值可以具有不同的数据类型(T1和T2),两个值可以分别用pair的两个公有函数first和second访问。

具体用法:

1.实例化:

  

   pair<string,string> p1("hello","word"); //调用default constructor   pair<double,int>    p2(1.0,1);//调用constructor   pair<double,int>    p3(p2); //调用 copy

2.对象的赋值以及make_pair()的应用:

     pair<string,string> p1;     pair<string,string> p2("good","good");     p1= p2;     p1= make_pair("hello","word");     p1 = pair<string,string>("nice","nice");


3.pair中元素的访问(first & second):

     pair<double,int>    p1(1.0,2);     pair<string,string> p2("hello","word");     int i = p1.second;  // i = 2     double d = p1.first; // d = 1.0     string s1 = p2.first; // s1 = hello     string s2 = p2.second; // word


4.pair数组与元素排序:

#include<iostream>#include<cstdio>#include<algorithm>using namespace std;pair<int,int>pa[100];int cmp(pair<int,int>a,pair<int,int>b){    if(a.first!=b.first)return a.first>b.first;    else return a.second<b.second;}int main(){    int a,b;    for(int i=0;i<5;i++)scanf("%d%d",&a,&b),pa[i]=make_pair(a,b);    sort(pa,pa+5,cmp);    for(int i=0;i<5;i++)printf("%d %d\n",pa[i].first,pa[i].second);    return 0;}