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

在c++ 98标准的STL中,只有一个pair<T1, T2>可以容纳两个不同的类型。我们知道在Python中,有一种tuple,可以把任意多类型的不同数据组成一组tuple,如今的tr1标准,也支持这种数据结构啦!!Boost中的tuple这个是从Boost中完全采纳的,所以先看Boost用法:声明:

boost::tuple < std::string, int, double > ta("str", 10, 5.5);

获取tuple的第几个元素:

ta.get<0>()
#include <boost/tuple/tuple.hpp>#include <string>#include <iostream>int main(){    boost::tuple < std::string, int, double > ta("str", 10, 5.5);    std::cout << ta.get<0>() << std::endl;    std::cout << ta.get<1>() << std::endl;    std::cout << ta.get<2>() << std::endl;    return 0;}

tr1中的用法然后再来看看标准tr1的用法,在get的时候略有不同。

#include <tr1/tuple>#include <string>#include <iostream>int main(){    std::tr1::tuple< std::string, int, double > ta("str", 10, 5.5);    std::cout << std::tr1::get<0>(ta) << std::endl;    std::cout << std::tr1::get<1>(ta) << std::endl;    std::cout << std::tr1::get<2>(ta) << std::endl;    return 0;}

tie用于unpack此外,tuple还提供了一个tie函数,用于unpack之:

#include <tr1/tuple>#include <string>#include <iostream>int main(){    std::tr1::tuple< std::string, int, double > ta("str", 10, 5.5);    // use 'tie' to unpack    std::string str_1;    int int_2;    double double_3;    std::tr1::tie(str_1, int_2, double_3) = ta;    std::cout << str_1 << std::endl;    std::cout << int_2 << std::endl;    std::cout << double_3 << std::endl;    return 0;}

 

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

相关文章:

你感兴趣的文章:

标签云: