C++ pair 的使用

pair的作用

C++ 中的 std::pair 是标准模板库 (STL) 提供的一个容器,它能够存储两个不同类型的数据作为一个整体,其中first:访问 pair 的第一个元素。second:访问 pair 的第二个元素。

复制代码
int main() {
    pair<string, int> p;
    //通过构造函数参数列表初始化
    p = make_pair("张三", 18);
    cout<<p.first << p.second<<endl;//打印结果 张三18
    // 初始化的时候赋值
    pair<string, int> pname("张三", 18);
    cout<<pname.first << pname.second<<endl;//打印结果 张三18
    return 0;
}

使用typedef

复制代码
#include <iostream>
#include <string>
using namespace std;
typedef pair<string,int> pp;
pp p1 = make_pair("张三", 18);
pp p2("张三", 18);
int main() {
     cout<<p1.first << p1.second<<endl;
     cout<<p2.first << p2.second<<endl;
    return 0;
}

pair 用在结构体中

复制代码
#include <iostream>
#include <string>
using namespace std;
struct config{
    pair<string, int> p;
    // 构造函数初始化
    config() : p{"张三", 18} {
        cout<<p.first << p.second<<endl;
    }
 };

int main() {
    config c;
    return 0;
}

还可以pair 与结构体绑定

复制代码
#include <iostream>
#include <string>
using namespace std;

struct config{
    pair<string, int> p;
    // 构造函数初始化
    config() : p{"张三", 18} {
        cout<<p.first << p.second<<endl;
    }
 };

int main() {
    config c;
    // 直接访问config结构体内的pair成员
    std::cout << "Integer value: " << c.p.second << ", String value: " << c.p.first << std::endl;
    // 或者利用C++17的结构化绑定来访问
    auto &[strValue, intValue] = c.p;
    std::cout << "Integer value: " << intValue << ", String value: " << strValue << std::endl;
    return 0;
}

pair 还可以用来 拷贝、赋值和比较

复制代码
std::pair<int, std::string> copyOfPair(myPair); // 拷贝构造
copyOfPair = anotherPair; // 赋值操作

if (myPair == anotherPair) { // 使用内置的等于运算符进行比较
    // ...
}
相关推荐
WHOVENLY2 分钟前
【javaScript】- 笔试题合集(长期更新,建议收藏,目前已更新至31题)
开发语言·前端·javascript
慌糖18 分钟前
流-为序列化解释
开发语言
LXS_3571 小时前
Day 18 C++提高 之 STL常用容器(string、vector、deque)
开发语言·c++·笔记·学习方法·改行学it
王琦03181 小时前
Python 函数详解
开发语言·python
胡伯来了1 小时前
13. Python打包工具- setuptools
开发语言·python
小鸡吃米…2 小时前
Python 中的多层继承
开发语言·python
deng-c-f2 小时前
Linux C/C++ 学习日记(53):原子操作(二):实现shared_ptr
开发语言·c++·学习
wanghowie2 小时前
01.07 Java基础篇|函数式编程与语言新特性总览
java·开发语言·面试
Cricyta Sevina2 小时前
Java IO 基础理论知识笔记
java·开发语言·笔记
一个不知名程序员www2 小时前
算法学习入门---结构体和类(C++)
c++·算法