c++中的元组

元组

用过python的朋友对元组肯定不陌生,这是python六大基础数据类型之一。
那么c++中有没有这种数据类型呢?答案是有的,不过需要包含相关头文件方可使用。

元组的特点

  • 元组的特性是元素值不可被修改。
  • 元组中可以存储不同数据类型的数据。
  • 元组是一个固定大小的不同类型值的集合,是泛化的std::pair。

c++中元组的使用

#include<iostream>
#include<tuple>
#include<string>
#include<vector>
using namespace std;

int main()
{
	//初始化列表赋值
	tuple<int, string, double,int> tu = { 1,"asd",1.35f,5};
	tuple<char, int, double> tu1;

	//给已定义的对象赋值
	tu1 = make_tuple('a', 1, 1.2f);
	//根据元素下标获取元组数据
	cout << get<0>(tu1) << endl;
	//根据数据类型获取元组数据
	cout << get<double>(tu) << endl;
	//通过tie进行解包tuple的各个元素的值
	char c1;
	int  n1;
	double d1;
	tie(c1, n1, d1) = tu1;
	cout << "first element:" << c1 << endl;
	cout << "second element:" << n1 << endl;
	cout << "third element:" << d1 << endl;

	//c++17新特性
	//auto [q, w, e] = tu1;
	//tuple还支持std容器,比如vector
	tuple<vector<int>, int> tu2 = { {1,2,3,4,5},5 };
	for (auto i : get<0>(tu2))
	{
		cout << i << " ";
	}
	cout << endl;
	//拼接两个元组
	auto newtuple = tuple_cat(tu, tu1);
	//获取元组元素个数
	//使用tuple_size需要知道tuple对象类型,类型推导使用 decltyple
	cout << "tuple size is:" << tuple_size<decltype(newtuple)>::value << endl;

	system("pause");
	return 0;
}


以上就是今天博主给大家分享的内容了,内容很简单,不过还是希望对大家有所帮助。

猜你喜欢

转载自blog.csdn.net/weixin_42494845/article/details/105716609
今日推荐