C++11——std::tuple

std::tuple是一个固定大小的不同类型值的集合,是泛化的std::pair。和c#中的tuple类似,但是比c#中的tuple强大得多。我们也可以把他当做一个通用的结构体来用,不需要创建结构体又获取结构体的特征,在某些情况下可以取代结构体使程序更简洁,直观。

样例:

// std::tuple 
class CTuple
{
public:
	CTuple() {}
	~CTuple() {}
	void Run();
private:
};
// 元组使用
void CTuple::Run()
{
	//创建tuple
	//auto t1 = make_tuple(1, "a1", "b1", "c1");
	std::tuple<int,string,string,string> t1 = std::make_tuple(1, "China", "中国", "北京");
	cout << get<0>(t1) << " ";	//取值
	cout << get<1>(t1) << " ";
	cout << get<2>(t1) << " ";
	cout << get<3>(t1) << " ";
	cout << endl;

	std::vector<tuple<int, string, string, string> > tv;
	tv.push_back(t1);
	tv.push_back(std::make_tuple(2, "ShanXI", "陕西", "西安"));
	tv.push_back(std::make_tuple(3, "SiChuan", "四川", "成都"));
	for (auto iter = tv.begin(); iter != tv.end(); iter++)
	{
		cout << get<0>(*iter) << " ";
		cout << get<1>(*iter) << " ";
		cout << get<2>(*iter) << " ";
		cout << get<3>(*iter) << endl;
	}

	// 解析tuple
	std::tuple<int, string, string, string> t3(10, "ShanXi", "山西", "太原");
	int nID;
	std::string strName1;
	std::string strName2;
	std::string strName3;
	std::tie(nID, strName1, strName2, strName3) = t3;				//则自动赋值到三个变量也可以只解析第三个值:
	std::tie(std::ignore, std::ignore, std::ignore, strName3) = t3; //std::ignore为占位符
	cout << "解析tuple:" << strName3 << endl;
}

调用:

int main()
{
	//测试std::tuple
	std::shared_ptr<CTuple> pTuple = std::make_shared<CTuple>();
	pTuple->Run();
	return 0;
}

运行结果:

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值