码迷,mamicode.com
首页 > 编程语言 > 详细

C++标准库 -- tuple

时间:2016-01-31 21:23:37      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

头文件:<tuple>

 

可访问属性

无(用get方法来访问数据)

 

可访问方法

swap(tuple) 和另外一个tuple交换值

 

其他相关方法

swap(t1, t2) 交换两个tuple
make_tuple(v1,v2..) 创建一个tuple
get<?>(tuple) 访问数据
tie(v1, v2..) 创建由reference构成的tuple

 

例子

  例子1:构造tuple

    tuple<int, float, string> t0;
    tuple<int, float, string> t1(1, 2.0, "three");
    auto t2 = make_tuple(2, 2, "asdf", 3.2);
    tuple<int, string> t3(make_pair(1, "kaima")); //use pair to init tuple
    auto t4 = t1;
    tuple<int, string> t5 = make_pair(1, "John");
  

 

  例子2:访问数据

    tuple<int, float, string> t1(1, 2.0, "three");
    cout << get<0>(t1) << " : " << get<1>(t1) << " : " << get<2>(t1) << endl;

 

  例子3:关系比较

    tuple<int, float, string> t1(1, 2.0, "three");
    tuple<int, float, string> t2(1, 1.0, "kaima");
    
    if(t1 > t2) // >= < <= == !=
        cout << "t1 > t2" << endl;

 

  例子4:交换值

    swap(t1, t2);
    t1.swap(t2);

 

  例子5:reference构成的tuple

    string s = "Hello";
    tuple<string&> t1(s);
    get<0>(t1) = "t1";
    cout << s << endl; //t1

    auto t2 = make_tuple(ref(s));
    get<0>(t2) = "t2";
    cout << s << endl; //t2

    auto t3 = tie(s);
    get<0>(t3) = "t3";
    cout << s << endl; //t3

 

其他

(1)“接受不定个数的实参”的构造函数被声明为explicit。

(2)元素个数:tuple_size<tupleType>::value

(3)第idx个元素的类型:tuple_element<idx, tupleType>::type

(4)连接tuple:tuple_cat(t1, t2..)

 

额外

使用以下代码可以直接cout一个tuple。

template <int IDX, int MAX, typename... Args>
struct PRINT_TUPLE {
    static void print(ostream& strm, const tuple<Args...>& t) {
        strm << get<IDX>(t) << (IDX+1==MAX ? "" : ",");
        PRINT_TUPLE<IDX+1, MAX, Args...>::print(strm, t); //recursion
    }
};

//end the recursion
template <int MAX, typename... Args>
struct PRINT_TUPLE<MAX, MAX, Args...> {
    static void print(ostream& strm, const tuple<Args...>& t) {
        //null
    }
};

template <typename... Args>
std::ostream& operator << (ostream& strm, const tuple<Args...>& t) {
    strm << "[";
        PRINT_TUPLE<0, sizeof...(Args), Args...>::print(strm, t);
        return strm << "]";
}

 

C++标准库 -- tuple

标签:

原文地址:http://www.cnblogs.com/programmer-kaima/p/5173650.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!