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

原文链接: https://www.cnblogs.com/zuixime0515/p/13127404.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C++中pair的使用

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/354950

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午8:58
下一篇 2023年3月2日 上午8:59

相关推荐