对组pair和元组tuple的基本使用

测试环境visual stdio 2019,C++14

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

//成对出现的数据,利用对组可以返回两个数据
void testPair()
{
	//cteate pair,first method
	pair<string, int>p("Tom", 20);
	cout << "name: " << p.first << " age: " << p.second << endl;
	//cteate pair,second method
	pair<string, int>p2 = make_pair ("jerry", 30);
	cout << "name: " << p2.first << " age: " << p2.second << endl;

}
/*

元组基本操作
关于元组的使用有三个核心的函数:
1. std::make_tuple: 构造元组
2. std::get: 获得元组某个位置的值
3. std::tie: 元组拆包
*/

template <typename T>
auto tuple_len(T& tpl) {
	return std::tuple_size<T>::value;
}

void testTuple()
{
	
	//name, age, height
	tuple<string, int, int>t1= make_tuple("tom", 20, 180);
	cout << "name: " << get<0>(t1) << " age: " << get<1>(t1) << " height: " << get<2>(t1) << endl;

	//运行期索引问题
	//std::get<> 依赖一个编译期的常量,所以下面的方式是不合法的:
	//int index = 1;//index为变量,不合法 (C++ 17 引入std::variant<> 处理)
	const int index = 1;//此时可编译通过
	std::get<index>(t1);
	cout << "std::get<index>(t1) age:" << std::get<index>(t1) << endl;

	//元组合并
	tuple<string, int, int>t2 = make_tuple("jerry", 30, 180);
	cout <<"std::tuple_size<T>::value: " <<std::tuple_size<tuple<string, int, int>>::value << endl;
	auto new_tuple = std::tuple_cat(t1, t2);
	//auto new_tuple = std::tuple_cat(t1, std::move(t2));
	auto res = tuple_len(new_tuple);
	cout << "tuple_len(new_tuple)" << res << endl;
	
	// 元组进行拆包
	string name;
	int age;
	int height;
	std::tie(name, age, height) = t1;
	cout << name << "," << age << "," << height << endl;

	//std::get 除了使用常量获取元组对象外,C++14 增加了使用类型来获取元组中的对象:
	std::tuple<std::string, double, double, int> t("123", 4.5, 6.7, 8);
	std::cout << std::get<std::string>(t) << std::endl;
	//std::cout << std::get<double>(t) << std::endl; // 非法, 引发编译期错误
	std::cout << std::get<3>(t) << std::endl;

}

int main()
{
	testPair();
	testTuple();
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值