pair 是 C++ 用来存储一对数据的模板,一个存 key,一个存 value,非常轻量、常用。


一、核心知识点

  • 功能:存储两个任意类型的数据(first + second)
  • 头文件:#include <utility> 或 #include <map>、#include <set> 都会自带
  • 常用场景:函数返回两个值、配合 map /set 使用、存储坐标点等

二、定义与初始化

// 1. 默认创建
pair<int, string> p1;

// 2. 直接赋值
pair<int, string> p2(10, "Tom");

// 3. 快速创建(最常用)
auto p3 = make_pair(20, "Jerry");

三、访问成员

  • p.first 第一个元素
  • p.second 第二个元素
#include <iostream>
#include <utility>
using namespace std;

int main() {
    pair<int, string> p = make_pair(666, "Hello Pair");
    
    cout << p.first << endl;   // 666
    cout << p.second << endl;  // Hello Pair
    return 0;
}

四、完整极简示例

#include <iostream>
#include <utility>
using namespace std;

int main() {
    // 创建
    pair<int, int> point(3, 5);
    
    // 访问
    cout << "x = " << point.first << endl;
    cout << "y = " << point.second << endl;
    
    // 修改
    point.first = 10;
    point.second = 20;
    cout << "新坐标:" << point.first << "," << point.second << endl;

    return 0;
}

//输出

x = 3
y = 5
新坐标:10,20

五、精炼总结

  1. pair = 两个值的小容器
  2. 访问:first、second
  3. 快速创建:make_pair(a,b)
  4. 轻量、高效、随处可用

更多推荐