C++编程->tuple(元组)

来源:互联网 发布:贵港淘宝培训课程 编辑:程序博客网 时间:2024/04/29 14:36

    类模板tuple 是类模板pair的一般化实现。

    元组是一种数据结构,其中的元素具有特定数目和序列。 一个元组示例是具有三个元素(称为 3 元组或者三)的数据结构,用来存储标识符,如一个人的名字在第一个元素中,年份在第二个元素中,此人当年的收入在在第三个元素中的。

元组通常有四种不同的使用方式:

  • 表示一组数据。 例如,元组可以表示一条数据库记录,并且其组件可以表示记录的各个字段。

  • 提供对数据集的轻松访问和操作。

  • 通过单个参数将多个值传递给一个方法。 例如,该Thread::Start(Object) 方法具有一个参数,可以使用该参数向在启动线程执行时的方法提供一个值。 如果将Tuple<T1, T2, T3> 对象作为方法参数提供,则可以提供具有三项数据的线程启动例程。


    类型tuple<T1,T2,T3....Tn>对象具有n个成员。以下是tuple的复制,初始化等相关操作。

    default (1)

constexpr tuple();
copy / move (2)
tuple (const tuple& tpl) = default;tuple (tuple&& tpl) = default;
implicit conversion (3)
template <class... UTypes>  tuple (const tuple<UTypes...>& tpl);template <class... UTypes>  tuple (tuple<UTypes...>&& tpl);
initialization (4)
explicit tuple (const Types&... elems);template <class... UTypes>  explicit tuple (UTypes&&... elems);
conversion from pair (5)
template <class U1, class U2>  tuple (const pair<U1,U2>& pr);template <class U1, class U2>  tuple (pair<U1,U2>&& pr);
allocator (6)
template<class Alloc>  tuple (allocator_arg_t aa, const Alloc& alloc);template<class Alloc>  tuple (allocator_arg_t aa, const Alloc& alloc, const tuple& tpl);template<class Alloc>  tuple (allocator_arg_t aa, const Alloc& alloc, tuple&& tpl);template<class Alloc,class... UTypes>  tuple (allocator_arg_t aa, const Alloc& alloc, const tuple<UTypes...>& tpl);template<class Alloc, class... UTypes>  tuple (allocator_arg_t aa, const Alloc& alloc, tuple<UTypes...>&& tpl);template<class Alloc>  tuple (allocator_arg_t aa, const Alloc& alloc, const Types&... elems);template<class Alloc, class... UTypes>  tuple (allocator_arg_t aa, const Alloc& alloc, UTypes&&... elems);template<class Alloc, class U1, class U2>  tuple (allocator_arg_t aa, const Alloc& alloc, const pair<U1,U2>& pr);template<class Alloc, class U1, class U2>  tuple (allocator_arg_t aa, const Alloc& alloc, pair<U1,U2>&& pr);

下面贴一段代码:

//初始化并赋值 foostd::tuple<int,char> foo (10,'x');//初始化并赋值 barauto bar = std::make_tuple ("test", 3.1, 14, 'y');//对bar第三个类型赋值std::get<2>(bar) = 100;                                    // access elementint myint; char mychar;//获取foo类型值并输出std::tie (myint, mychar) = foo;                            // unpack elementsstd::cout << "foo contains: ";std::cout <<"the foo's first value is :"<<std::get<0>(foo) << ' ';std::cout <<"the foo's second valve is : " <<std::get<1>(foo) << '\n';//获取tuple中元素的个数int size1=std::tuple_size<decltype(bar)>::value;cout<<"bar size is :"<<size1<<endl;//新建一个结构体struct s1{vector<int>l1;float l2;list<int>l3;};//赋值s1 s1_var;s1_var.l1.push_back(12);s1_var.l2=23;s1_var.l3.push_back(13);tuple<s1,int,float>tuple3(s1_var,15,23.2);int size2=std::tuple_size<decltype(tuple3)>::value;cout<<"tuple3 size is :"<<size2<<endl;//输出tuple3的值cout<<"output tuple3's the second var : "<<get<0>(tuple3).l2<<endl;cout<<endl;

运行后结果如下:

foo contains: the foo's first value is
bar size is :4
tuple3 size is :3
output tuple3's the second var : 23



0 0
原创粉丝点击