C++ 参考手册

位置:首页 > C++ 参考手册 >工具库 >std::pair > std::pair<T1,T2>::pair

pair( std::piecewise_construct_t,
      std::tuple<Args1...> first_args,

      std::tuple<Args2...> second_args );
(C++11 èµ·)
(C++20 前)
template< class... Args1, class... Args2 >

constexpr pair( std::piecewise_construct_t,
                std::tuple<Args1...> first_args,

                std::tuple<Args2...> second_args );
(C++20 èµ·)
pair( const pair& p ) = default;
(7)
pair( pair&& p ) = default;
(8) (C++11 èµ·)


构造新的 pair 。

1) 默认构造函数。值初始化 pair 的两个元素 first 和 second 。

  • 此构造函数参与重载决议,当且仅当 std::is_default_constructible_v<first_type> 与 std::is_default_constructible_v<second_type> 均为 true 。
  • 此构造函数为 explicit ,当且仅当 first_type 或 second_type 不可隐式默认构造。
(C++11 èµ·)

2) 以 x 初始化 first 并以 y 初始化 second 。

(C++11 èµ·)

3) 以 std::forward<U1>(x) 初始化 first 并以 std::forward<U2>(y) 初始化 second 。

4) 以 p.first 初始化 first 并以 p.second 初始化 second 。

  • 此构造函数参与重载决议,当且仅当 std::is_constructible_v<first_type, const U1&> å’Œ std::is_constructible_v<second_type, const U2&> 均为 true 。
  • 此构造函数为 explicit ,当且仅当 std::is_convertible_v<const U1&, first_type> 为 false 或 std::is_convertible_v<const U2&, second_type> 为 false 。
(C++11 èµ·)

5) 以 std::forward<U1>(p.first) 初始化 first 并以 std::forward<U2>(p.second) 初始化 second 。

6) 转发 first_args 的元素到 first 的构造函数并转发 second_args 的元素到 second 的构造函数。这是能用于构造不可复制不可移动类型的 pair 的仅有的非默认构造函数。

7) 复制构造函数为默认,且若两个元素的复制满足 constexpr 函数的要求则为 constexpr 。

8) 移动构造函数为默认,且若两个元素的移动满足 constexpr 函数的要求则为 constexpr 。

参数

x - 初始化此 pair 首元素的值
y - 初始化此 pair 第二元素的值
p - 用于初始化此 pair 两个元素的值的 pair
first_args - 初始化此 pair 首元素的构造函数参数的 tuple
second_args - 初始化此 pair 第二元素的构造函数参数的 tuple

异常

不抛异常,除非指定操作之一(如元素的构造)抛出。

缺陷报告

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

DR 应用于 出版时的行为 正确行为
N4387 C++11 某些构造函数曾为 explicit ,阻止了有用的行为 使大多数构造函数为条件性 explicit
LWG 2510 C++11 默认构造函数为隐式 使之为条件性 explicit

示例

#include <utility>
#include <string>
#include <complex>
#include <tuple>
#include <iostream>
 
int main()
{
    std::pair<int, float> p1;
    std::cout << "Value-initialized: "
              << p1.first << ", " << p1.second << '\n';
 
    std::pair<int, double> p2(42, 0.123);
    std::cout << "Initialized with two values: "
              << p2.first << ", " << p2.second << '\n';
 
    std::pair<char, int> p4(p2);
    std::cout << "Implicitly converted: "
              << p4.first << ", " << p4.second << '\n';
 
    std::pair<std::complex<double>, std::string> p6(
                    std::piecewise_construct, 
                    std::forward_as_tuple(0.123, 7.7),
                    std::forward_as_tuple(10, 'a'));
    std::cout << "Piecewise constructed: "
              << p6.first << ", " << p6.second << '\n';
}

输出:

Value-initialized: 0, 0
Initialized with two values: 42, 0.123
Implicitly converted: *, 0
Piecewise constructed: (0.123,7.7), aaaaaaaaaa

参阅

创建一个 pair 对象,其类型根据各实参类型定义
(函数模板)