我們在C++中都用過pair.pair是一種模板類型,其中包含兩個數據值,兩個數據的類型可以不同.pair可以使用make_pair構造
pairp = make_pair(1, "a1");
#include#include
上面的做法明顯很麻煩,在C++11中引入了變長參數模板,所以發明了新的數據類型:tuple,tuple是一個N元組,可以傳入1個, 2個甚至多個不同類型的數據,避免了嵌套pair的丑陋做法,通過make_tuple()創建元組,通過get<>()來訪問元組的元素
#include#include #include 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 > tv; tv.push_back(make_tuple(1, "a1", "b1", "c1")); tv.push_back(make_tuple(2, "a2", "b2", "c2")); vector >::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; }