在 C++ 中,std::pair 是一个模板类,用于将两个不同类型的值组合成一个单一对象。它定义在 头文件中,是标准库中非常常用的组件之一。

基本用法

  1. 创建和初始化
#include <utility>  // 包含 pair 的头文件
#include <string>
#include <iostream>

int main() {
    // 方法1: 直接初始化
    std::pair<int, std::string> p1(42, "hello");

    // 方法2: 使用 make_pair (自动推导类型)
    auto p2 = std::make_pair(3.14, "world");

    // 方法3: C++17 起支持的类模板参数推导
    std::pair p3(123, 456.789);  // 自动推导为 pair<int, double>

    return 0;
}
  1. 访问元素
std::pair<int, std::string> p(10, "example");

// 访问第一个元素
int first = p.first;  // 10

// 访问第二个元素
std::string second = p.second;  // "example"
  1. 比较操作

pair 支持比较运算符 (==, !=, <, <=, >, >=),按字典序比较:

std::pair<int, int> a(1, 2);
std::pair<int, int> b(1, 3);

if (a < b) {  // 先比较 first,再比较 second
    std::cout << "a is less than b";
}
  1. 结构化绑定 (C++17)
auto [x, y] = std::make_pair(5, "hello");
// x 是 int 5,y 是 const char* "hello"

常见使用场景 函数返回多个值‌

std::pair<bool, std::string> checkValue(int val) {
    if (val > 0) {
        return {true, "positive"};
    } else {
        return {false, "non-positive"};
    }
}

作为 map 的元素‌

#include <map>
std::map<int, std::string> myMap;
myMap.insert(std::make_pair(1, "one"));
// 或
myMap.emplace(2, "two");

排序和优先队列‌

std::vector<std::pair<int, std::string>> vec;
vec.emplace_back(3, "three");
vec.emplace_back(1, "one");
std::sort(vec.begin(), vec.end());  // 按 first 排序

注意事项 pair 的元素可以是任意类型,包括另一个 pair pair 的默认构造函数会对内置类型进行值初始化 C++11 后可以使用 std::tie 来解包 pair(比结构化绑定更早的方法) 示例代码

#include <iostream>
#include <utility>
#include <string>

int main() {
    // 创建 pair
    std::pair<int, std::string> student(101, "Alice");
    
    // 访问元素
    std::cout << "ID: " << student.first << ", Name: " << student.second << "\n";
    
    // 修改元素
    student.second = "Bob";
    
    // 使用结构化绑定
    auto [id, name] = student;
    std::cout << "New student: " << id << " - " << name << "\n";
    
    return 0;
}

std::pair 是 C++ 中简单但功能强大的工具,特别适合需要将两个值组合在一起的情况。在 C++11 之后,还有 std::tuple 可以处理更多元素的组合。