tuple(不定数值组)的操作
1.初始化 见Init()//class tuple<>构造函数是
explicit的,因此不支持隐式转换
2.其他tuple的特性 见special
3.tuple的输出 见output()等
#include<iostream>
#include<tuple>
using namespace std;
void Init()
{
//常规初始化
tuple<int, double, string> t1(3, 3.14, "Wh");//...
//用pair初始化tuple
pair<int, double> p(2, 3);
tuple<int, double> t2(p);
//other
int a = 3;
double b = 3.14;
//tie()更多见 tieIntuple()
tuple<int&, double&> p3 = tie(a, b);
auto p4 = make_tuple(ref(a), ref(b));
}
void tieIntuple()
{
int a = 4;
double b = 4.2;
//tie返回的类型是tuple<int&,double&>
tuple<int, double> p1 = tie(a, b);
tuple<int&, double&> p2 = tie(a, b);
--a;
b = 5.3;
cout << get<0>(p1) << ends << get<1>(p1) << endl;
cout << get<0>(p2) << ends << get<1>(p2) << endl;
//通过tie()得到特定位置的值
double d = 0.0;
tie(ignore, d) = p2;
cout << d << endl;
}
void special()
{
//得到类型个数
cout << tuple_size < tuple<int, double, double>>::value;
//得到指定位置类型
tuple_element<1, tuple<int, double, double>>::type d = 3.14;
cout << d << endl;
//将多个tuple串接成一个tuple
auto tp = tuple_cat(make_tuple(3.22, 3), tie(d));
}
template<int Index,int Max,typename ...Args>
struct PRINT_TUPLE
{
static void print(ostream& os, const tuple<Args...>& t)
{
os << get<Index>(t) << (Index + 1 == Max ? "" : ",");
PRINT_TUPLE<Index + 1, Max, Args...>::print(os, t);
}
};
template<int Max,typename ...Args>
struct PRINT_TUPLE<Max, Max, Args...>
{
//无实例调用必须声明为静态方法
static void print(ostream& os,const tuple<Args...>& t)
{
}
};
template<typename ...Args>
ostream& operator <<(ostream& os, const tuple<Args...>& t)
{
os << "[";
PRINT_TUPLE<0, sizeof...(Args), Args...>::print(os, t);
return os << "]";
}
void output()
{
tuple<int, double, double> t(3, 2.33, 3.22);
cout << t;
}
int main()
{
//Init();
//tieIntuple();
//special();
output();
system("pause");
return 0;
}
本文介绍了C++中的tuple操作,包括初始化、特殊特性及输出方法。详细讲解了tuple的初始化过程,强调了class tuple<>构造函数的显式特性,不支持隐式转换。同时探讨了tuple的其他特性,并展示了如何进行tuple的输出操作。
714

被折叠的 条评论
为什么被折叠?



