参考:http://blog.csdn.net/aspnet_lyc/article/details/30980465
我们在C++中都用过pair.pair是一种模板类型,其中包含两个数据值,两个数据的类型可以不同.pair可以使用make_pair构造
- pair<int, string> p = make_pair(1, "a1");
如果传入的参数为多个,那么就需要嵌套pair,如下代码
// map:含多重嵌套的pair
void Test()
{
// map<int, tuple<string, string, string>>
map<int, pair<string, pair<string, string>>> m;
auto temp1(make_pair("b1", "c1"));
// assert(typeid(temp1) == typeid(pair<string, string>)); // assert(false);
// assert(typeid(temp1) == typeid(pair<char const*, char const*>));
auto temp2(make_pair("a1", temp1));
// assert(typeid(temp2) == typeid(pair<char const*, pair<char const*, char const*> >));
m.insert(make_pair(2, temp2));
auto temp3(make_pair("b2", "c2"));
// assert(typeid(temp3) == typeid(pair<char const*, char const*>));
auto temp4(make_pair("a2", temp3));
// assert(typeid(temp4) == typeid(pair<char const*, pair<char const*, char const*> >));
m.insert(make_pair(1, temp4));
// 遍历
for (auto itr1=m.begin(); itr1!=m.end(); itr1++)
{
// assert(typeid(itr1) == typeid(map<int, pair<string, pair<string, string> > >::iterator));
cout << itr1->first << " ";
auto temp2 = itr1->second;
cout << temp2.first << " ";
auto temp1 = temp2.second;
cout << temp1.first << " ";
cout << temp1.second << endl;
}
}
上面的做法明显很麻烦,在C++11中引入了变长参数模板,所以发明了新的数据类型:tuple,tuple是一个N元组,可以传入1个, 2个甚至多个不同类型的数据,避免了嵌套pair的丑陋做法,通过make_tuple()创建元组,通过get<>()来访问元组的元素
Test的等价实现:
// Test的等价实现
void Test2()
{
map<int, tuple<string, string, string>> m;
auto temp1(make_tuple("a1", "b1", "c1"));
// assert( typeid(temp1) == typeid(tuple<string, string, string>) ); // assert(false);
// assert(typeid(temp1) == typeid(tuple<char const*, char const*, char const*>));
m.insert(make_pair(2, temp1));
auto temp2(make_tuple("a2", "b2", "c2"));
// assert(typeid(temp2) == typeid(tuple<char const*, char const*, char const*>));
m.insert(make_pair(1, temp2));
// 遍历
for (auto itr1=m.begin(); itr1!=m.end(); itr1++)
{
// assert(typeid(itr1) == typeid(map<int, tuple<string, string, string> >::iterator)); // not const_iterator
cout << itr1->first << " ";
auto t1 = itr1->second;
cout << get<0>(t1) << " "
<< get<1>(t1) << " "
<< get<2>(t1) << " "
<< endl;
}
}
元素是tuple的vector
// 元素是tuple的vector
void Test3()
{
auto t1 = make_tuple(1, "a1", "b1", "c1");
// assert(typeid(t1) == typeid(tuple<int, char const*, char const*, char const*>));
// cout << typeid(t1).name() << endl; // class std::tuple<...>
get<0>(t1) = 10;
get<2>(t1) = "d3";
cout << get<0>(t1) << " "
<< get<1>(t1) << " "
<< get<2>(t1) << " "
<< get<3>(t1) << " "
<< endl;
vector<tuple<int, string, string, string> > tv;
tv.push_back(make_tuple(2, "a1", "b1", "c1"));
tv.push_back(make_tuple(1, "a2", "b2", "c2"));
for (auto itr=tv.begin(); itr!=tv.end(); itr++)
{
// assert(typeid(itr) == typeid(vector<tuple<int, string, string, string> >::iterator));
cout << get<0>(*itr) << " "
<< get<1>(*itr) << " "
<< get<2>(*itr) << " "
<< get<3>(*itr) << endl;
}
}