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) { // 使用内置的等于运算符进行比较
    // ...
}
相关推荐
Ulyanov1 天前
高保真单脉冲雷达导引头回波生成:Python建模与实践
开发语言·python·仿真·系统设计·单脉冲雷达
Mr_WangAndy1 天前
C++数据结构与算法_线性表_数组_概念动态数组,刷题
c++·二分查找·数组刷题·数组字符串逆序·零移动·有序数组的平方
阿猿收手吧!1 天前
【C++】jthread:优雅终止线程新方案
开发语言·c++
lly2024061 天前
《JavaScript 实例》
开发语言
十五年专注C++开发1 天前
C++中各平台表示Debug的宏
开发语言·c++·debug
张小凡vip1 天前
Python异步编程实战:基于async/await的高并发实现
开发语言·python
玩c#的小杜同学1 天前
源代码保卫战:给C# 程序(混淆、加壳与反逆向实战)
开发语言·笔记·c#
阿猿收手吧!1 天前
【C++】Ranges:彻底改变STL编程方式
开发语言·c++
云游云记1 天前
php 随机红包数生成
开发语言·php·随机红包
程序员林北北1 天前
【前端进阶之旅】JavaScript 一些常用的简写技巧
开发语言·前端·javascript