std::pair是什么类型?std::make_pair()怎么用?
时间: 2025-07-01 20:42:42 浏览: 15
### C++ `std::pair` 类型定义
`std::pair` 是标准模板库 (STL) 中的一个容器适配器,用于存储两个具有不同类型的值。它通常被用来表示键值对或简单的二元组。`std::pair` 定义在 `<utility>` 头文件中。
#### 类型定义
`std::pair` 的类型定义如下:
```cpp
template<class T1, class T2>
struct pair {
typedef T1 first_type;
typedef T2 second_type;
T1 first;
T2 second;
// 构造函数和其他成员函数...
};
```
其中:
- `T1` 和 `T2` 表示两种不同的数据类型。
- 成员变量 `first` 存储第一个值,`second` 存储第二个值[^3]。
可以通过访问 `first` 和 `second` 来操作 `std::pair` 中的数据。
---
### `std::make_pair` 使用方法
`std::make_pair` 是一个辅助函数,用于简化创建 `std::pair` 对象的过程。它的作用是通过传入的两个参数自动生成一个 `std::pair` 实例,并推导出相应的类型。
#### 函数签名
`std::make_pair` 的声明如下:
```cpp
template< class T1, class T2 >
constexpr std::pair<V1,V2> make_pair( T1&& t, T2&& u );
```
这里:
- 参数 `t` 和 `u` 被转发到 `std::pair` 的构造函数中。
- 返回值是一个 `std::pair<V1, V2>`,其中 `V1` 和 `V2` 是由编译器自动推导出来的类型[^1]。
#### 示例代码
以下是一些常见的用法示例:
##### 1. 基本用法
```cpp
#include <iostream>
#include <utility>
int main() {
auto p = std::make_pair(10, 3.14);
std::cout << "First: " << p.first << ", Second: " << p.second << std::endl;
}
```
输出结果为:
```
First: 10, Second: 3.14
```
##### 2. 配合其他 STL 容器使用
`std::make_pair` 经常与其他 STL 容器一起使用,比如 `std::map` 或 `std::vector<std::pair<T1, T2>>`。
```cpp
#include <iostream>
#include <vector>
#include <utility>
int main() {
std::vector<std::pair<int, double>> vec;
vec.push_back(std::make_pair(1, 2.5));
vec.push_back(std::make_pair(2, 3.7));
for (const auto& item : vec) {
std::cout << "(" << item.first << ", " << item.second << ")" << std::endl;
}
}
```
输出结果为:
```
(1, 2.5)
(2, 3.7)
```
##### 3. 自动类型推导
由于 `auto` 关键字的存在,可以省去显式指定返回类型的操作。
```cpp
#include <iostream>
#include <utility>
int main() {
auto p = std::make_pair("Hello", 42);
std::cout << "String: " << p.first << ", Number: " << p.second << std::endl;
}
```
输出结果为:
```
String: Hello, Number: 42
```
##### 4. 结合 `std::tie` 提取值
`std::tie` 可以将多个左值引用绑定到 `std::pair` 的成员上,从而提取它们的值[^2]。
```cpp
#include <iostream>
#include <utility>
int main() {
int a;
double b;
std::pair<int, double> p = {42, 3.14};
std::tie(a, b) = p;
std::cout << "a: " << a << ", b: " << b << std::endl;
}
```
输出结果为:
```
a: 42, b: 3.14
```
---
### 总结
- `std::pair` 是一种轻量级的容器,适合存储两个固定类型的值。
- `std::make_pair` 提供了一种便捷的方式来创建 `std::pair` 对象,无需手动指定类型。
- 这两者经常配合使用于各种场景,例如作为映射表项 (`std::map`) 或复杂数据结构的一部分。
---
阅读全文
相关推荐




















