std::get(std::pair)

来自cppreference.com
< cpp‎ | utility‎ | pair
 
 
 
 
在标头 <utility> 定义
template<std::size_t I, class T1, class T2 >

typenamestd::tuple_element<I, std::pair<T1,T2>>::type&

    get(std::pair<T1, T2>& p )noexcept;
(1) (C++11 起)
(C++14 起为 constexpr)
template<std::size_t I, class T1, class T2 >

consttypenamestd::tuple_element<I, std::pair<T1,T2>>::type&

    get(conststd::pair<T1,T2>& p )noexcept;
(2) (C++11 起)
(C++14 起为 constexpr)
template<std::size_t I, class T1, class T2 >

typenamestd::tuple_element<I, std::pair<T1,T2>>::type&&

    get(std::pair<T1,T2>&& p )noexcept;
(3) (C++11 起)
(C++14 起为 constexpr)
template<std::size_t I, class T1, class T2 >

consttypenamestd::tuple_element<I, std::pair<T1,T2>>::type&&

    get(conststd::pair<T1,T2>&& p )noexcept;
(4) (C++11 起)
(C++14 起为 constexpr)
template<class T, class U >
constexpr T& get(std::pair<T, U>& p )noexcept;
(5) (C++14 起)
template<class T, class U >
constexprconst T& get(conststd::pair<T, U>& p )noexcept;
(6) (C++14 起)
template<class T, class U >
constexpr T&& get(std::pair<T, U>&& p )noexcept;
(7) (C++14 起)
template<class T, class U >
constexprconst T&& get(conststd::pair<T, U>&& p )noexcept;
(8) (C++14 起)
template<class T, class U >
constexpr T& get(std::pair<U, T>& p )noexcept;
(9) (C++14 起)
template<class T, class U >
constexprconst T& get(conststd::pair<U, T>& p )noexcept;
(10) (C++14 起)
template<class T, class U >
constexpr T&& get(std::pair<U, T>&& p )noexcept;
(11) (C++14 起)
template<class T, class U >
constexprconst T&& get(conststd::pair<U, T>&& p )noexcept;
(12) (C++14 起)

元组式接口从对偶中提取元素。

1-4) 若索引 I 不是 01 则基于索引的重载无法编译。
5-12) 若类型 TU 相同则基于类型的重载无法编译。

目录

[编辑]参数

p - 要提取内容的对偶

[编辑]返回值

1-4)I==0 则返回到 p.first 的引用,若 I==1 则返回到 p.second 的引用。
5-8) 返回到 p.first 的引用。
9-12) 返回到 p.second 的引用。

[编辑]示例

#include <iostream>#include <utility>   int main(){auto p =std::make_pair(1, 3.14);std::cout<<'('<<std::get<0>(p)<<", "<<std::get<1>(p)<<")\n";std::cout<<'('<<std::get<int>(p)<<", "<<std::get<double>(p)<<")\n";}

输出:

(1, 3.14) (1, 3.14)

[编辑]缺陷报告

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

缺陷报告 应用于 出版时的行为 正确行为
LWG 2485 C++11 (按索引)
C++14 (按类型)
无对于 const pair&& 的重载 添加重载

[编辑]参阅

结构化绑定(C++17) 绑定指定的名字到初始化式的子对象或元组元素[编辑]
元组式访问指定的元素
(函数模板)[编辑]
访问 array 的一个元素
(函数模板)[编辑]
以给定索引或类型(如果类型唯一)读取 variant 的值,错误时抛出异常
(函数模板)[编辑]
std::ranges::subrange 获得迭代器或哨位
(函数模板)[编辑]
std::complex 获取到实部或虚部的引用
(函数模板)[编辑]
close