STL标准库-Tuple

技术在于交流、沟通,本文为博主原创文章转载请注明出处并保持作品的完整性

在前面我介绍过一次tuple,今天在书上也看到了tuple,那就在写一次吧.

tuple(元组),他的内部可以放任意类型的变量(有点类似结构体),前面介绍过它的递归继承,这次直接看基本使用吧

1.创建和取出元素

void testTuple()
{
    tuple<string, int, int, complex<double>> t;
    
    tuple<int, float, string> t1(41, 6.3, "nico");
    
    auto t2 = make_tuple(22,44,"make_tuple");
    
    //operator=
    get<1>(t1) = get<1>(t2);
    
    //取出指定下标元素 get<index>(tuple)
    cout << "testTuple operator=: " << get<1>(t1) << endl; 
}

 

2.比较大小 : 比较原则为,先比较元素个数,然后按其元素的比较规则比较大小(比较大小的两个tuple,所含元素类型必须相同)

    void testTupleCompare()
    {
        tuple<int, float, string> t1(41, 6.3, "nico");
        auto t2 = make_tuple(22,44,"make_tuple");
        if(t1 < t2)
            cout<< "testTupleCompare t1 < t2" << endl;
        else
            cout << "testTupleCompare t1 > t2" << endl;
    }

 

 

 

3.分割元素 tie()

    void testTupleTie()
    {
        tuple<int, float, string> t1(41, 6.3, "nico");
        int a;
        int b;
        string str;
        tie(a,b,str) = t1;
        cout << "testTupleTie a="<< a << " b=" << b << " str="<< str << endl;
    }

 

 

 

4.tuple_size和tuple_element(取出元素类型)

    void testTupleSizeAndElement()
    {
        tuple<int, float, string> t(41, 6.2, "nico");
        cout << "testTupleSizeAndElement tuple_size = " << (tuple_size<decltype(t)>::value) << endl;//取出tuple元素个数

        typedef tuple_element<0,decltype(t)>::type T1;;//取出tuple元素类型
        typedef tuple_element<1,decltype(t)>::type T2;
        typedef tuple_element<2,decltype(t)>::type T3;

        cout << "index[0] element: " << typeid(T1).name()<<endl
                  << "index[1] element: " << typeid(T2).name()<< endl
                        << "index[2] element: " << typeid(T3).name() << endl;
    }

 

 

 

5.拼接tuple tuple_cat

    void testTupleCat()
    {
        tuple<int> t1(41);
        auto t2 = make_tuple(22);
        auto t3 = tuple_cat(t1,t2);
        cout << __FUNCTION__ << " t3: " << get<0>(t3) << " " << get<1>(t3) << endl;
    }

 

 

 

6.交换函数 swap()

    void testTupleSwap()
    {
        tuple<int> t1(41);
        auto t2 = make_tuple(22);
        t1.swap(t2);
        cout << __FUNCTION__ << " t1 " << get<0>(t1) << endl;
        cout << __FUNCTION__ << " t2 " << get<0>(t2) << endl;
    }

 

 

 

参考侯捷<<STL源码剖析>> 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值