zoukankan      html  css  js  c++  java
  • 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);
  • 相关阅读:
    C#循环页面form中控件
    鼠标放到按钮上页面样式发生变化
    access INSERT INTO 语句的语法错误
    更改水晶报表数据源
    C# byte[]与string互转
    禁用右键
    showModalDialog IE9 报错
    ListBox 循环删除当前项
    showModalDialog 刷新本页面,不重新发送信息,则无法刷新网页,Page_PreRender
    敏捷模式开发(转)
  • 原文地址:https://www.cnblogs.com/LjwCarrot/p/8688299.html
Copyright © 2011-2022 走看看