c++11 标准模板(STL)(std::tuple)(一)

定义于头文件 <tuple>

template< class... Types >
class tuple;

(C++11 起)

类模板 std::tuple 是固定大小的异类值汇集。它是 std::pair 的推广。

若 (std::is_trivially_destructible_v<Types> && ...) 为 true ,则 tuple 的析构函数是平凡的。

(C++17 起)

模板形参

Types...-tuple 所存储的元素的类型。支持空列表。

成员函数

(构造函数)

构造新的 tuple
(公开成员函数)

operator=

赋值一个 tuple 的内容给另一个
(公开成员函数)

swap

交换二个 tuple 的内容
(公开成员函数)

非成员函数

make_tuple

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

tie

创建左值引用的 tuple,或将 tuple 解包为独立对象
(函数模板)

forward_as_tuple

创建转发引用的 tuple
(函数模板)

tuple_cat

通过连接任意数量的元组来创建一个tuple
(函数模板)

std::get(std::tuple)

元组式访问指定的元素
(函数模板)

operator==operator!=operator<operator<=operator>operator>=

按字典顺序比较 tuple 中的值
(函数模板)

std::swap(std::tuple)

(C++11)

特化 std::swap 算法
(函数模板)

辅助类

tuple_size

在编译时获得 tuple 的大小
(类模板特化)

tuple_element

获得指定元素的类型
(类模板特化)

std::uses_allocator<std::tuple>

(C++11)

特化 std::uses_allocator 类型特征
(类模板特化)

ignore

用 tie 解包 tuple 时用来跳过元素的占位符
(常量)

推导指引(C++17 起)

注意

C++17 前,函数不能用列表初始化返回 tuple

std::tuple<int, int> foo_tuple() 
{
  return {1, -1};  // C++17 前错误
  return std::make_tuple(1, -1); // 始终有效
}

调用示例

#include <tuple>
#include <iostream>
#include <string>
#include <typeinfo>
#include <stdexcept>

std::tuple<double, char, std::string> get_student(int id)
{
    if (id == 0)
    {
        return std::make_tuple(3.8, 'A', "Lisa Simpson");
    }
    if (id == 1)
    {
        return std::make_tuple(2.9, 'C', "Milhouse Van Houten");
    }
    if (id == 2)
    {
        return std::make_tuple(1.7, 'D', "Ralph Wiggum");
    }
    throw std::invalid_argument("id");
}

int main()
{
    auto student0 = get_student(0);
    std::cout << "typeid(student0).name(): "
              << typeid(student0).name() << std::endl;
    std::cout << "ID: 0, "
              << "GPA: " << std::get<0>(student0) << ", "
              << "grade: " << std::get<1>(student0) << ", "
              << "name: " << std::get<2>(student0) << std::endl;

    double gpa1 = 0.0;
    char grade1 = '\0';
    std::string name1 = "";
    std::tie(gpa1, grade1, name1) = get_student(1);
    std::cout << "ID: 1, "
              << "GPA: " << gpa1 << ", "
              << "grade: " << grade1 << ", "
              << "name: " << name1 << std::endl;
    return 0;
}

输出

typeid(student0).name(): St5tupleIJdcNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEEE
ID: 0, GPA: 3.8, grade: A, name: Lisa Simpson
ID: 1, GPA: 2.9, grade: C, name: Milhouse Van Houten

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值