C++的键值对pair和元组tuple

pair常见的操作函数

在这里插入图片描述
测试:

//pair
void test01()
{
	int i = 0;
	auto p = std::make_pair(std::ref(i), std::ref(i));
	++p.first;
	++p.second;
	cout << i << endl;

	std::pair<char, char> pp = std::make_pair('x', 'y');
	char c;
	std::tie(std::ignore, c) = pp;
	cout << c << endl;
	
	//说白了pair就是两个值绑定到一起,只要能够访问到这两个值就行,piar也是一个模板的函数,可以存放的数据的类型也是不限制的,可以放类,string,int等等。
	//可以使用first和secend访问到他的值
}

元组的函数

元组是什么,元组就是存放不同的数据类型,不想vector那样,存放的数据的类型必须是一致的,存放了一个学生类,后面的数据也必须是学生类,tuple不同,可以存放不同的数据类型,有了这个之后可以方便我们使用,比如,一个小的结构体数据可以使用元组代替了。
在这里插入图片描述

测试:

//tuple元组
void test02()
{
	tuple<string, int, int, complex<double>> t;
	tuple<int, float, string>t1(41, 6.0, "nice");
	cout << get<0>(t1) << " "<< get<1>(t1) << " "<<get<2>(t1) << " " << endl;

	auto t2 = make_tuple(22, 44, "nico");
	//get<1>(t1) = get<1>(t2);
	if (t1 > t2)//比较的是每一个值
	{
		t1 = t2;
	}
	cout << get<0>(t1) << " " << get<1>(t1) << " " << get<2>(t1) << " " << endl;

	//修改tuple中的一个值
	std::string s;
	auto x = make_tuple(s);
	std::get<0>(x) = "my value";
	auto y = make_tuple(ref(s));
	std::get<0>(y) = "my value1";
	cout << get<0>(y) << endl;
	cout << get<0>(x) << endl;

	std::tuple<int, float, std::string>tt(77, 11.22, "test test");
	int i;
	float f;
	std::string ss;
	std::make_tuple(std::ref(i), std::ref(f), std::ref(s)) = tt;
	std::tie(i, f, ss) = tt;

	//获取元素个数
	//拼接
	int n = 99;
	auto tp=tuple_cat(std::make_tuple(42, 6.5, "world"), std::tie(n));
	cout << get<0>(tp) << " " << get<1>(tp) << " " << get<2>(tp) << " " << get<3>(tp) << endl;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值