以下帖子介绍的比较详细:
C++的 tuple_c++ tuple-CSDN博客
tuple 是 C++11 新标准里的类型,它是一个类似 pair 类型的模板。tuple 是一个固定大小的不同类型值的集合,是泛化的 std::pair。我们也可以把它当做一个通用的结构体来用,不需要创建结构体又获取结构体的特征,在某些情况下可以取代结构体使程序更简洁直观。std::tuple 理论上可以有无数个任意类型的成员变量,而 std::pair 只能是2个成员,因此在需要保存3个及以上的数据时就需要使用 tuple 元组,而且每个确定的 tuple 类型的成员数目是固定的。
「注意」:使用tuple的相关操作需要包含相应头文件:#include<tuple>
tuple 所支持的操作
make_tuple(v1,v2,v3,v4…vn) :返回一个给定初始值初始化的tuple,类型从初始值推断。
t1 == t2 :当两个tuple具有相同数量的成员且成员对应相等时。
t1 != t2 :与上一个相反。
get(t) :返回t的第i个数据成员。
tuple_size::value :给定了tuple中成员的数量。
通过 std::tie 解包tuple,通过tie解包后,t中三个值会自动赋值给三个变量。
通过 tuple_cat 连接多个 tuple,如:
auto t2 = tuple_cat(t1, make_pair("Foo", "bar"), t1, tie(n));
下面是一些用法测试:
#include <iostream>
#include <tuple>
using namespace std;
int main()
{
auto t3 = make_tuple(1, 2, "3c", 'F');
cout<< "the 1st elem: " << get<0>(t3) << ", is of type: " << typeid(get<0>(t3)).name()<< endl;
cout<< "the 2nd elem: " << get<1>(t3) << ", is of type: " << typeid(get<1>(t3)).name()<< endl;
cout<< "the 3rd elem: " << get<2>(t3) << ", is of type: " << typeid(get<2>(t3)).name()<< endl;
cout<< "the 4th elem: " << get<3>(t3) << ", is of type: " << typeid(get<3>(t3)).name()<< endl;
return 0;
}
该程序的输出结果是:
tuple似乎非常有用,比如在设计统一接口时,传入不定数量和不同类型的参数时候。
#include <iostream>
#include <tuple>
using namespace std;
void func(tuple<int> tp){printf("in func 1\n");}
void func(tuple<int , int > tp){printf("in func 2\n");}
void func(tuple<int , int , const char*> tp){printf("in func 3\n");}
void func(tuple<int , int , const char* , char > tp){ printf("in func 4\n");}
int main()
{
auto t3 = make_tuple(1, 2, "3c", 'F');
const int i = 0;
cout<< "the 1st elem: " << get<i>(t3) << ", is of type: " << typeid(get<0>(t3)).name()<< endl;
cout<< "the 2nd elem: " << get<1>(t3) << ", is of type: " << typeid(get<1>(t3)).name()<< endl;
cout<< "the 3rd elem: " << get<2>(t3) << ", is of type: " << typeid(get<2>(t3)).name()<< endl;
cout<< "the 4th elem: " << get<3>(t3) << ", is of type: " << typeid(get<3>(t3)).name()<< endl;
auto t2 = make_tuple(1, 2, "3c");
auto t1 = make_tuple(1, 2);
auto t0 = make_tuple(1);
func(t3);
func(t2);
func(t1);
func(t0);
return 0;
}
输入结果为:
更为集中的话还可以这样:
void func(tuple<int> tp){printf("in func 1\n");}
void func(tuple<int , int > tp){printf("in func 2\n");}
void func(tuple<int , int , const char*> tp){printf("in func 3\n");}
void func(tuple<int , int , const char* , char > tp){ printf("in func 4\n");}
#if 1
void minimum(auto tp) //Here should use C++14 std to compile because auto param here.
{
int size = tuple_size<decltype(tp)>::value;
cout << "input size: " << size << endl;
func(tp);
}
#endif
int main()
{
auto t3 = make_tuple(1, 2, "3c", 'F');
auto t2 = make_tuple(1, 2, "3c");
auto t1 = make_tuple(1, 2);
auto t0 = make_tuple(1);
minimum(t3);
minimum(t2);
minimum(t1);
minimum(t0);
return 0;
}
输出结果是:文章来源:https://www.toymoban.com/news/detail-782237.html
文章来源地址https://www.toymoban.com/news/detail-782237.html
到了这里,关于C++标准学习--tuple的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!