C++11中的tuple应用:让函数返回多个值

本文介绍了C++11标准中引入的Tuple类型及其应用。通过示例代码展示了如何使用Tuple返回多个值,并解释了Tuple作为Pair泛化的概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在没有tuple之前,如果函数需要返回多个值,则必须定义一个结构体,有了C++11,可以基于tuple直接做了,下面是个示例:

// 编译:g++ -std=c++11 -g -o x x.cpp
#include <tuple> // tuple头文件
#include <stdio.h>
#include <string>
using namespace std;

// 函数foo返回tuple类型
tuple<int, string> foo();

int main()
{
    // 两个不同类型的返回值a和b
    int a;
    string b;

    // 注意tie的应用
    tie(a, b) = foo();
    printf("%d => %s\n", a, b.c_str());

    // 注意tuple是一个可以容纳不同类型元素的容器
    // ,在C++11中,下面的x一般使用auto定义,这样简洁些。
    tuple<int, string, char, float> x = make_tuple(2014, "tupule", 'x', 5.30);
    printf("%d, %s, %c, %.2f\n", get<0>(x), get<1>(x).c_str(), get<2>(x), get<3>(x));
    
    return 0;
}

tuple<int, string> foo()
{
    // 用make_tuple来构造一个tuple
    return make_tuple(2014, "tuple");
}

从上述的代码,可以看出tuple是对pair的泛化。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值