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;
}

运行结果:

发布了84 篇原创文章 · 获赞 2 · 访问量 5247

猜你喜欢

转载自blog.csdn.net/finghting321/article/details/104969925
今日推荐