c++ tr1和Boost中,tuple、tie的用法

在c++ 98标准的STL中,只有一个pair<T1, T2>可以容纳两个不同的类型。

我们知道在Python中,有一种tuple,可以把任意多类型的不同数据组成一组tuple,如今的tr1标准,也支持这种数据结构啦!!

Boost中的tuple
这个是从Boost中完全采纳的,所以先看Boost用法:

声明:

1
boost::tuple < std::string, int, double > ta("str", 10, 5.5);
获取tuple的第几个元素:

1
ta.get<0>()
01
#include <boost/tuple/tuple.hpp>
02
#include <string>
03
#include <iostream>
04

05
int main()
06
{
07
boost::tuple < std::string, int, double > ta("str", 10, 5.5);
08
std::cout << ta.get<0>() << std::endl;
09
std::cout << ta.get<1>() << std::endl;
10
std::cout << ta.get<2>() << std::endl;
11
return 0;
12
}
tr1中的用法
然后再来看看标准tr1的用法,在get的时候略有不同。


01
#include <tr1/tuple>
02
#include <string>
03
#include <iostream>
04

05
int main()
06
{
07
std::tr1::tuple< std::string, int, double > ta("str", 10, 5.5);
08
std::cout << std::tr1::get<0>(ta) << std::endl;
09
std::cout << std::tr1::get<1>(ta) << std::endl;
10
std::cout << std::tr1::get<2>(ta) << std::endl;
11
return 0;
12
}
tie用于unpack
此外,tuple还提供了一个tie函数,用于unpack之:

view source


print?


01
#include <tr1/tuple>
02
#include <string>
03
#include <iostream>
04

05
int main()
06
{
07
std::tr1::tuple< std::string, int, double > ta("str", 10, 5.5);
08
// use 'tie' to unpack
09
std::string str_1;
10
int int_2;
11
double double_3;
12
std::tr1::tie(str_1, int_2, double_3) = ta;
13
std::cout << str_1 << std::endl; [url=http://wo-cn.com/wujinjianzhuang]无尽剑装[/url] http://wo-cn.com/wujinjianzhuang
14
std::cout << int_2 << std::endl;
15
std::cout << double_3 << std::endl;
16
return 0;
17
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值