STL--pair学习笔记

<pair>

STL<utility>描述的一个模板类pair,用来表示一个二元组或元素对,其中的两个数据值的数据类型可以不同。

pair模板类对象有两个成员:first second  分别表示首元素和尾元素。

 

#include<utility>              //头文件
pair<string,double>p1;                 //使用默认的构造函数
pair<string,double>p2(“apple”,7.0);    //调用构造函数初始化
pair<string,double>p3(p2)              //调用拷贝构造函数
pair<string,double>*p4=new pair<string,double>(“banana”,7.0); //初始化pair指针

 

如果pair类型的使用比较繁琐,因为如果要定义多个形同的pair类型的时候,可以时候typedef简化声明:

例:

typedef pair<string,int>student;
student stu1(“Tim”,2017);
student stu2(“Marry”,2018);

访问:通过first  second 来访问

pair<string,int>student(“Tim”,2017);
Cout<<student.first<<’ ‘<<student.second<<endl;        //输出则为:Tim 2017        

赋值:直接定义一个pair对象外,如需即时生成一个pair对象,可以调用<utility>中的一个模板函数:make_pair  

#include<iostream>
#include<utility>
using namespace std;
int main()
{
    typedef struct pair<string,int> stu;                //
    stu stu1=make_pair("apple",1);
    cout<<stu1.first<<' '<<stu1.second<<endl;
    stu1.first="banana";
    stu1.second=2;
    cout<<stu1.first<<' '<<stu1.second<<endl;
    return 0;
 } 
//输出结果:     apple  1
//            banana 2

<utility>中已经定义了pair上的六个比较运算符:<><=>===!=,其规则是先比较firstfirst相等时再比较second,这符合大多数应用的逻辑。当然,也可以通过重载这几个运算符来重新指定自己的比较逻辑。 

Pair  排序:

typedef pair<int,int>h;
 bool cmp(const h &a,const h &b)            //引用调用
 {
     return a.first<b.first;                //排序对象以pair的第一个元素first排序,升序
 }                                    //要以second为排序的对象,将first改为second
bool cmp(const P &a,const P&b)
{
     if(a.first!=b.first)return a.first<b.first;
     if(a.second!=b.second)return a.second<b.second;
}//先按照first升序,若first相同按second升序

//主函数里
sort(st,st+n,cmp);

 

posted @ 2018-04-01 21:10  _Carrot  阅读(537)  评论(0编辑  收藏  举报