• C++pair类型


    标准库类型--pair类型定义在utility头文件中定义

     本文地址:http://www.cnblogs.com/archimedes/p/cpp-pair.html,转载请注明源地址。

    1、pair的创建和初始化

    pair包含两个数值,与容器一样,pair也是一种模板类型。但是又与之前介绍的容器不同,在创建pair对象时,必须提供两个类型名,两个对应的类型名的类型不必相同

    pair<string,string>anon;
    pair<string,int>word_count;
    pair<string, vector<int> >line;

    当然也可以在定义时为每个成员提供初始化式:

    pair<string,string>author("James","Joy");

    pair类型的使用相当的繁琐,如果定义多个相同的pair类型对象,可以使用typedef简化声明:

    typedef pair<string,string> Author;
    Author proust("March","Proust");
    Author Joy("James","Joy");

    2、pair对象的操作

    对于pair类,可以直接访问其数据成员:其成员都是公有的,分别命名为first和second,只需要使用普通的点操作符

    string firstBook;
    if(author.first=="James" && author.second=="Joy")
        firstBook="Stephen Hero";

    3、生成新的pair对象

    除了构造函数,标准库还定义了一个make_pair函数,由传递给它的两个实参生成一个新的pair对象

    pair<string, string> next_auth;
    string first,last;
    while(cin>>first>>last) {
        next_auth=make_pair(first,last);
        //...
    }

    还可以用下列等价的更复杂的操作:

    next_auth=pair<string,string>(first,last);

    由于pair的数据成员是公有的,因而可如下直接地读取输入:

    pair<string, string> next_auth;
    while(cin>>next_auth.first>>next_auth.last) {
        //...
    }

    4、编程实践

    练习:编写程序读入一系列string和int型数据,将每一组存储在一个pair对象中,然后将这些pair对象存储在vector容器

    #include<iostream>
    #include<string>
    #include<vector>
    #include<utility>
    using namespace std;
    
    int main()
    {
        pair<string, int>p;
        typedef vector< pair<string, int> > VP;
        VP vp;
        while(cin>>p.first>>p.second)
        {
            vp.push_back(make_pair(p.first,p.second));
            
        }
        VP::iterator it;
        for(it=vp.begin(); it!=vp.end(); it++)
            cout<<it->first<<","<<it->second<<endl;
    
        return 0;
    }
  • 相关阅读:
    vue学习简单入门
    Python3基础学习
    MySQL数据库索引详解
    使用nginx部署多个前端项目
    基于SpringBoot2.x和tkMapper快速搭建微服务项目脚手架工程
    安装篇-Linux安装maven3.5.2
    安装篇-安装maven3.6.1
    安装篇-安装Idea2019.3.3
    安装篇-jdk1.8安装
    【错误解决】Intellj(IDEA) warning no artifacts configured
  • 原文地址:https://www.cnblogs.com/wuyudong/p/cpp-pair.html
Copyright © 2020-2023  润新知