C++11元组了解

元组函数介绍

完整介绍参见

C++11元组(tuple)的使用 - 码到城攻C++11 新增了 std::tuple 容器用于构造一个元组,进而囊括多个返回值https://www.codecomeon.com/posts/220/
tuple相关的一共有4个函数:

make_tuple


用于创建 tuple:

auto tup1 = std::make_tuple("Hello World!", 'a', 3.14, 0);


上述代码创建了一个 tuple <const char*, char, double, int> 类型的元组。可以看出,在tuple之中可以是完全不同的数据类型。

tie


用于拆开tuple

auto tup1 = std::make_tuple(3.14, 1, 'a');
double a;
int b;
char c;
std::tie(a, b, c) = tup1;


这样做的结果是 a = 3.14, b = 1, c = ‘a’。

如果不想要某一位的值,可以直接将其用ignore代替。

std::tie(ignore, b, c) = tup1;


tuple_cat


用于连接tuple

std::tuple<float, string> tup1(3.14, "pi");
std::tuple<int, char> tup2(10, 'a');
auto tup3 = tuple_cat(tup1, tup2);


将tup1和tup2连起来就成了tup3。

元组中元素操作


对于获取tuple中元素,有以下操作

get


获取第 i 个元素的值:

std::tuple<float, string> tup1(3.14, "pi");
cout << get<0>(tup1);


这样就输出了tup1中的第一个元素3.14.

tuple_element


获取tuple中特定元素数据类型

std::tuple_element<0, decltype(tup1)>::type


这样就获取到了tup1中第一个元素的数据类型。

注意:获取到的就是数据类型,如int,char。而不是写有“int”或者“char”的字符串。

size


获取tuple中元素个数

std::tuple<float, string> tup1(3.14, "pi");
cout << tuple_size<decltype(tup1)>::value;


输出结果为2,表示该tuple中有两个元素。

实验代码


#include <iostream>
#include <tuple>
int main() {
    // make_tuple: 用于创建tuple
    auto tup1 = std::make_tuple("Hello World!", 'a', 3.14, 0);
    // tie: 用于拆开tuple
    std::string a;
    char b;
    double c;
    int d;
    std::tie(a, b, c, d) = tup1;
    std::cout << a << b << c << d << std::endl;
    // tuple_cat: 用于连接tuple
    std::tuple<int, char> tup2(10, 'a');
    auto tup3 = std::tuple_cat(tup1, tup2);
    // get: 获取第 i 个元素的值
    std::cout << std::get<5>(tup3) << std::endl;
    // tuple_element: 获取tuple中特定元素数据类型
    std::tuple_element<0, decltype(tup3)>::type test;
    // size: 获取tuple中元素个数
    std::cout << std::tuple_size<decltype(tup3)>::value << std::endl;
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值