名稱空間
變體
操作

std::make_pair

來自 cppreference.com
< 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
型別,這導致無法傳遞陣列
將這些
型別更改為值型別