目录
万能存储器:C++中的元胞数组
什么是元胞数组?
元胞数组英文名字为“tuple”,他是个数据类型,但不是基本的数据类型,它更像是一个包含有各种数据类型的大杂烩,元胞数组本质上也是数组,但是它颠覆了数组的普遍规则,即普通数组是一个仅包含一种数据类型的集合体,而元胞数组则是混杂了多种数据类型。它突破了数组一般规律的限制,为我们带来了诸多便利。
元胞数组怎么用?
C++打开了支持元组的大门。std::tuple就是实现元组的模板类,您可使用任意数量的元素来实例化这个模板类,其中每个元素都可为任何类型。要访问这些元素,可使用标准库函数std::get。
代码示例
Decltype是什么?该如何使用?
定义:
Decltype全称declared type,意为已被声明的类型。它的作用是用于判断已定义的数据类型并返回该数据类型。
如何使用详见代码示例:
#include <iostream>
#include <tuple>
#include <string>
using namespace std;
int main()
{
// 这里应用了元胞数组的初始化,元胞数组不可以遍历只可以用"对象名=make_tuple()"或"对象名()"初始化
tuple < string, char, float > stud = make_tuple("超级霸霸强", 'f', 99.99);
string name;
char sex;
float mark;
tie(name, sex, mark) = stud; cout << name << "的性别是" << sex << ";成绩是" << mark << endl;
/*decltype说白了就是一个类型名称,和int,float...相同,但是decltype存在的意义在于decltype(变量或表达式)可用于判断变量或
表达式的返回值的数据类型并且返回一个数据类型的名称*/
decltype(stud) stud1 = make_tuple("强哥", 'm', 88.88); // 声明一个与stud变量同类型的元胞数组
tie(name, sex, mark) = stud1;
cout << name << "的性别是" << sex << ";成绩是" << mark << endl;
}
Decltype的实质:
我们要知道使用decltype可以声明一个与已被声明过的变量同数据类型的变量。
Tuple_cat是什么?该如何使用?
Tuple_cat的作用:
Tuple_cat全称为tuple catenate,意为元胞数组连接。顾名思义,该函数主要用于两个元胞数组的连接。
如何使用详见代码:
#include <iostream>
#include <tuple>
#include <string>
using namespace std;
int main()
{
tuple<string, int, char> StudIntro("超级霸霸强", 7, 'f');
tuple<float, float> StudBody(98.5, 185.5);
auto Stud = tuple_cat(StudIntro, StudBody);
string Name;
int StudName;
char Sex;
float Weight, Height;
tie(Name, StudName, Sex, Weight, Height) = Stud;
cout << Name << "的student number为" << StudName << ";sex为" << Sex << ";weight为" << ";height为" << Height << endl;
}
Tuple_size是什么?如何使用?
Tuple_size的作用:
计算元胞数组的总元素的个数,其实就是计算数组的长度。
使用详见代码:
#include <iostream>
#include <tuple>
using namespace std;
int main()
{
tuple<int, char, double> mytuple(10, 'a', 3.14);
std::cout << "mytuple has ";
std::cout << tuple_size<decltype(mytuple)>::value;
std::cout << " elements." << '\n';
return 0;
}
其中有疑问?
#include <iostream>
#include <string>
#include <tuple>
using namespace std;
int main()
{
tuple<string, int, char> stud("大明", 7, 'f');
cout << tuple_size<decltype(stud)>::value << endl; // 固定形式要记住
// 为什么要用decltype(stud)?
}
那让我们来看一看函数tuple_size函数的定义吧:
函数原型中表明函数的形参是元胞数组的定义类型,我们要知道decltype函数就是用来返回变量或函数返回值的数据类型的。
Tuple_element什么作用?如何使用?
Tuple_element的作用:
数组元素类型的别名。
使用方法详见代码示例:
#include <iostream>
#include <string>
#include <tuple>
using namespace std;
int main()
{
//可以直接初始化
std::tuple<int, double, std::string> t(64, 128.0, "Caroline");
//可以通过"std::tuple_element<0, decltype(t)>::type"获取元素类型
std::tuple_element<1, decltype(t)>::type cnt = std::get<1>(t);
std::cout << "cnt = " << cnt << std::endl;
}
代码演示:
注:size_t的使用
一个基本的无符号整数的C / C + +类型,该类型的大小可选择,因变量的取值而变。因此,它可以存储在理论上是可能的任何类型的数组的最大大小。