命名空间
变体
操作

std::make_pair

来自 cppreference.cn
< cpp‎ | 工具库‎ | pair
 
 
 
 
在头文件 <utility> 中定义
template< class T1, class T2 >
std::pair<T1, T2> make_pair( T1 x, T2 y );
(C++11 前)
template< class T1, class T2 >
std::pair</*V1*/, /*V2*/> make_pair( T1&& x, T2&& y );
(C++11 起)
(C++14 起为 constexpr)
(C++20 前)
template< class T1, class T2 >

constexpr std::pair<std::unwrap_ref_decay_t<T1>,
                    std::unwrap_ref_decay_t<T2>>

    make_pair( T1&& x, T2&& y );
(C++20 起)

创建一个 std::pair 对象,从参数类型推导出目标类型。

给定类型 std::decay<T1>::typeU1std::decay<T2>::typeU2,类型 /*V1*//*V2*/ 定义如下:

(C++11 起)
(C++20 前)

目录

[编辑] 参数

x, y - 用于构造 pair 的值

[编辑] 返回值

std::pair<T1, T2>(x, y)

(C++11 前)

std::pair</*V1*/, /*V2*/>(std::forward<T1>(x), std::forward<T2>(y))

(C++11 起)
(C++20 前)

std::pair<std::unwrap_ref_decay_t<T1>, std::unwrap_ref_decay_t<T2>>
    (std::forward<T1>(x), std::forward<T2>(y))

(C++20 起)

[编辑] 示例

#include <functional>
#include <iostream>
#include <utility>
 
int main()
{
    int n = 1;
    int a[5] = {1, 2, 3, 4, 5};
 
    // build a pair from two ints
    auto p1 = std::make_pair(n, a[1]);
    std::cout << "The value of p1 is "
              << '(' << p1.first << ", " << p1.second << ")\n";
 
    // build a pair from a reference to int and an array (decayed to pointer)
    auto p2 = std::make_pair(std::ref(n), a);
    n = 7;
    std::cout << "The value of p2 is "
              << '(' << p2.first << ", " << *(p2.second + 2) << ")\n";
}

输出

The value of p1 is (1, 2)
The value of p2 is (7, 3)

[编辑] 缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 发布时的行为 正确的行为
LWG 181 C++98 参数类型是 const-reference
类型,这导致无法传递数组
将这些
类型更改为值类型