C++ tuple 学习笔记(笔误请指出)
首先,我们知道了pair这种东西,它的每一组可以存储两个类型的值,并封装。
那么现在的tuple就是pair的延伸拓展。
tuple可以将多个类型的值封装起来。
首先来了解一下它的定义方式:
tuple<T1 , T2 , ... , Tn> 名称;在上面的代码中实现了定义一个有多个类型的元组。
在下面代码中就定义了一个tuple。
#include<bits/stdc++.h>
using namespace std;
int main() {tuple<string,int,double> stu;return 0;
}这份代码定义了一个可以同时存储三种类型的元素stu元组。
聪明的你想到了这个东西可以实现和结构体相同的功能。
见:
#include<bits/stdc++.h>
using namespace std;
struct stu{int n;string s;double pi;
};
pair<int,pair<string,double> > stu2;//通过使用pair嵌套实现和stu相似的功能
tuple<int,string,double> stu3;//通过使用tuple实现和stu相似的功能
int main() {return 0;
}怎么赋值?
见以下代码:
tuple<int,string,double> stu(123,"",3.14);在这份代码中stu中的int类型的值为123,string类型的值为空,double类型的值为3.14。其他的以此类推……
怎么访问元素值?
可以使用:get<类型>(元组名)来获取。
推荐:get<类型索引>(元组名)来获取。
见以下代码:
#include<bits/stdc++.h>
using namespace std;
//tuple<int,int,string,double> error(2,123,"",3.14);
tuple<int,string,double> stu(123,"",3.14);
int main() {cout<<get<0>(stu)<<"\n";/*stu中:int索引为0,string索引为1,double索引为2也就是说,索引编号从0开始。 */ cout<<get<int>(stu)<<"\n";
// cout<<get<int>(error);//将发生错误,不推荐原因(用于没有重复类型的情况) return 0;
}获取某个类型索引的类型
#include<bits/stdc++.h>
using namespace std;
tuple<int,string,double,char,bool,float,long long,short> stu(123,"",3.14,'a',0,1.0,10020135,1);
int main() {cout<<typeid(get<0>(stu)).name()<<"\n";cout<<typeid(get<1>(stu)).name()<<"\n";cout<<typeid(get<2>(stu)).name()<<"\n";cout<<typeid(get<3>(stu)).name()<<"\n";cout<<typeid(get<4>(stu)).name()<<"\n";cout<<typeid(get<5>(stu)).name()<<"\n";cout<<typeid(get<6>(stu)).name()<<"\n";cout<<typeid(get<7>(stu)).name()<<"\n";
// typeid(变量名).name()能够获取某个值的类型,x为long long,其余基本以首字母决定 return 0;
}