zoukankan      html  css  js  c++  java
  • C++中pair的使用

    pair的数据定义

    C++ pair的参考网站的介绍如下所示---->

    std::pair is a class template that provides a way to store two heterogeneous objects as a single unit. A pair is a specific case of a std::tuple with two elements.

    直接翻译过来就是说pair是将两个不同的数据直接整合成一个数据单元的类模板,是tuple的一个特例,需要注意的是这两个数据可以是相同类型也可以是不同的类型

    pair的原型定义

    template<class T1, class T2> struct pair;
    

    其中T1, T2 pair的两个数据数据类型,pair也有两个数据成员firstsecond

    pair常用的成员函数

    函数名 作用
    make_pair 创建pair对象
    std::tuple_size<std::pair> 获取pair的大小
    std::tuple_element<std::pair> 返回pair的数据
    std::get(std::pair) 返回pair的数据

    示例程序

    void TestPair()
    {
        // make pair array and output first value
        std::pair<std::string, std::string> BookInfo[] = { {"Amazon bool", "123456"}, {"Google Book", "9876543210"} };
        std::cout << "pair info --> " << BookInfo[0].first << " socond value --> " << BookInfo[0].second << std::endl;
    
        std::pair<std::string, int> AgeofPerson("Alex", 23);
        std::cout << "AgeofPerson first value --> " << AgeofPerson.first << " second value ---> " << AgeofPerson.second << std::endl;
    
        // modify the data manually
        std::pair<int, std::string> DictionaryPage;
        DictionaryPage.first = 12;
        DictionaryPage.second = "Affluent";
    
        std::cout << "DictionaryPage info first value --> " << DictionaryPage.first << " second value --> " << DictionaryPage.second << std::endl;
    
        // use the make_pair function to make a pair apprenetly
        std::pair<int, int> data;
        data = std::make_pair(1, 2);
        std::cout << "make_pair data info ---> first value ---> " << data.first << " second value ---> " << data.second << std::endl;
    
    }
    

    输出结果

    pair info --> Amazon bool socond value --> 123456
    AgeofPerson first value --> Alex second value ---> 23
    DictionaryPage info first value --> 12 second value --> Affluent
    make_pair data info ---> first value ---> 1 second value ---> 2
    
  • 相关阅读:
    VC编译器
    位域
    位域2
    函数调用时刻的堆栈情况
    字节对齐2
    Python学习笔记(6)while循环、while嵌套
    Python学习笔记(7)字符串Str
    Python学习笔记(3)输出、输入、输出输入综合小练习
    Python学习笔记(1)Python介绍、解释器、第一个python程序、注释
    Python学习笔记(4)运算符、运算符小练习
  • 原文地址:https://www.cnblogs.com/zuixime0515/p/13127404.html
Copyright © 2011-2022 走看看