Chinaunix首页 | 论坛 | 博客
  • 博客访问: 6086859
  • 博文数量: 2759
  • 博客积分: 1021
  • 博客等级: 中士
  • 技术积分: 4091
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-11 14:14
文章分类

全部博文(2759)

文章存档

2019年(1)

2017年(84)

2016年(196)

2015年(204)

2014年(636)

2013年(1176)

2012年(463)

分类: C/C++

2014-06-06 02:43:25

在没有tuple之前,如果函数需要返回多个值,则必须定义一个结构体,有了C++11,可以基于tuple直接做了,下面是个示例:
点击(此处)折叠或打开
  1. // 编译:g++ -std=c++11 -g -o x x.cpp
  2. #include <tuple> // tuple头文件
  3. #include <stdio.h>
  4. #include <string>
  5. using namespace std;

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

  8. int main()
  9. {
  10.     // 两个不同类型的返回值a和b
  11.     int a;
  12.     string b;

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

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

  23. tuple<int, string> foo()
  24. {
  25.     // 用make_tuple来构造一个tuple
  26.     return make_tuple(2014, "tuple");
  27. }

从上述的代码,可以看出tuple是对pair的泛化。
阅读(543) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~