std::pair学习
std::pair 是 C++ 标准库中的一个通用容器,定义在 <utility> 头文件中。它将两个可能不同类型的数据组合成一个对象。
一、基本用法:
#include <utility>
#include <iostream>
int main() {
// 1. 创建 pair
std::pair<int, std::string> p1(1, "apple");
auto p2 = std::make_pair(2, "banana"); // 推荐:类型自动推导
// 2. C++17 起可以使用 CTAD
std::pair p3(3, "cherry"); // 自动推导为 pair<int, const char*>
// 3. 访问元素
std::cout << p1.first << ", " << p1.second << std::endl; // 1, apple
// 4. 比较操作(字典序)
std::pair<int, int> a(1, 2);
std::pair<int, int> b(1, 3);
std::cout << (a < b) << std::endl; // true (1==1, 2<3)
return 0;
}
二、常用操作
#include <utility>
#include <tuple> // C++11 tie
// 修改值
std::pair<int, std::string> p(1, "hello");
p.first = 2;
p.second = "world";
// 交换
std::pair<int, int> x(1, 2);
std::pair<int, int> y(3, 4);
x.swap(y); // x 变成 (3,4),y 变成 (1,2)
// 结构化绑定 (C++17)
auto [id, name] = std::make_pair(100, "Alice");
std::cout << id << ", " << name << std::endl;
// tie 解包 (C++11)
int a;
std::string b;
std::tie(a, b) = std::make_pair(200, "Bob");
三、常用应用场景
1、函数返回两个值
std::pair<int, bool> divide(int dividend, int divisor) {
if (divisor == 0) return {0, false}; // 失败
return {dividend / divisor, true}; // 成功
}
// 使用
auto [result, success] = divide(10, 2);
if (success) {
std::cout << "Result: " << result << std::endl;
}
2、作为map的键值对
#include <map>
std::map<std::string, int> scores;
scores.insert({"Alice", 95});
scores.insert(std::make_pair("Bob", 87));
// 遍历 map
for (const auto& [name, score] : scores) {
std::cout << name << ": " << score << std::endl;
}
3、关联容器中存储两个值
std::vector<std::pair<int, std::string>> vec;
vec.emplace_back(1, "one");
vec.emplace_back(2, "two");
// 排序(默认按 first,然后 second)
std::sort(vec.begin(), vec.end());
推荐在现代 C++ 中使用 auto [a, b] = pair 和 std::make_pair 来提高代码可读性。