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

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; 无尽剑装 http://wo-cn.com/wujinjianzhuang
14
std::cout << int_2 << std::endl;
15
std::cout << double_3 << std::endl;
16
return 0;
17
}