Namespaces
Variants

std::make_pair

来自 zh.cppreference.net
 
 
 
 
定义于头文件 <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++20 前)
(C++14 起 constexpr)
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>::type 为 U1 且 std::decay<T2>::type 为 U2,类型 /*V1*/ 和 /*V2*/ 定义如下:

  • 若 U1 为 std::reference_wrapper<X>,则 /*V1*/ 为 X&;否则 /*V1*/ 为 U1。
  • 若 U2 为 std::reference_wrapper<Y>,则 /*V2*/ 为 Y&;否则 /*V2*/ 为 U2。
(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};
    // 从两个整数构建 pair
    auto p1 = std::make_pair(n, a[1]);
    std::cout << "p1 的值为 "
              << '(' << p1.first << ", " << p1.second << ")\n";
    // 从 int 引用和数组(退化为指针)构建 pair
    auto p2 = std::make_pair(std::ref(n), a);
    n = 7;
    std::cout << "p2 的值为 "
              << '(' << 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 参数类型为常量引用类型,导致无法传递数组 将这些类型改为值类型