蓝天

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

在没有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的泛化。

posted on 2014-05-30 15:34  #蓝天  阅读(2406)  评论(0编辑  收藏  举报

导航