首页 > 代码库 > C++11 新特性之 tuple

C++11 新特性之 tuple

我们在C++中都用过pair.pair是一种模板类型,其中包含两个数据值,两个数据的类型可以不同.pair可以使用make_pair构造

pair<int, string> p = make_pair(1, "a1");

如果传入的参数为多个,那么就需要嵌套pair,如下代码


#include <iostream>
#include <map>
using namespace std;

int main()
{	
	//<int, string, string, string> ,注意:在嵌套模板实参列表中应当使用‘> >’而非‘>>’
	map<int, map<string, map<string, string> > > m; 
	
	map<string, string> temp1;
	temp1.insert(make_pair("b1", "c1"));
	
	map<string, map<string, string> > temp2;
	temp2.insert(make_pair("a1", temp1));
	
	m.insert(make_pair(1, temp2));
	
	map<string, string> temp3;
	temp3.insert(make_pair("b2", "c2"));
	
	map<string, map<string, string> > temp4;
	temp4.insert(make_pair("a2", temp3));
	
	m.insert(make_pair(2, temp4));
	
	//遍历
	map<int, map<string, map<string, string> > >::const_iterator itr1;
	map<string, map<string, string> >::const_iterator itr2;
	map<string, string>::const_iterator itr3;
	
	for (itr1=m.begin(); itr1!=m.end(); itr1++)
	{
		cout << itr1->first << " ";
		itr2 = (itr1->second).begin();
	    cout << itr2->first << " ";
	    itr3 = (itr2->second).begin();
	    cout << itr3->first << " ";
	    cout << itr3->second << endl;
	}
	
	pair<int, string> p = make_pair(1, "a1");
	
	return 0;
}

上面的做法明显很麻烦,在C++11中引入了变长参数模板,所以发明了新的数据类型:tuple,tuple是一个N元组,可以传入1个, 2个甚至多个不同类型的数据,避免了嵌套pair的丑陋做法,通过make_tuple()创建元组,通过get<>()来访问元组的元素

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

int main()
{	
	auto t1 = make_tuple(1, "a1", "b1", "c1");
	cout << get<0>(t1) << " ";
	cout << get<1>(t1) << " ";
	cout << get<2>(t1) << " ";
	cout << get<3>(t1) << " ";
	cout << endl;
	
	vector<tuple<int, string, string, string> > tv;
	tv.push_back(make_tuple(1, "a1", "b1", "c1"));
	tv.push_back(make_tuple(2, "a2", "b2", "c2"));
	
	vector<tuple<int, string, string, string> >::iterator itr;
	for (itr=tv.begin(); itr!=tv.end(); itr++)
	{
		cout << get<0>(*itr) << " ";
		cout << get<1>(*itr) << " ";
		cout << get<2>(*itr) << " ";
		cout << get<3>(*itr) << endl;
	}
	
	return 0;
}