C++11 標準新引入了一種類模板,命名為 tuple(中文可直譯為元組)。tuple 最大的特點是:實例化的對象可以存儲任意數量、任意類型的數據。tuple 的應用場景很廣泛,例如當需要存儲多個不同類型的元素時,可以使用 tuple;當函數需要返回多個數據時,可以將這些數據存儲在 tuple 中,函數只需返回一個 tuple 對象即可。
1.聲明并初始化一個tuple對象
std::tuple<int, float, std::string> t1(41, 6.3, "nico");std::cout << "tuple<int, float, std::string>, sizeof = " << sizeof(t1) << std::endl;std::cout << "t1: " << std::get<0>(t1) << ' ' << std::get<1>(t1) << ' ' << std::get<2>(t1) << std::endl; // 獲取下標 0 1 2處的元素
2.利用auto關鍵字,自動獲取類型
auto t2 = std::make_tuple(22, 44, "hello");std::cout << "t2 sizeof = " << sizeof(t2) << std::endl;std::cout << "t2: " << std::get<0>(t2) << ' ' << std::get<1>(t2) << ' ' << std::get<2>(t2) << std::endl;
3.tuple比大小操作??
// 比大小操作if(t1 < t2){std::cout << "t1 < t2" << std::endl;}else if(t1 > t2){std::cout << "t1 > t2" << std::endl;}else{std::cout << "t1 = t2" << std::endl;}
4.tie綁定操作進行復制
std::tuple<int, float, std::string> t3(77, 1.1, "more light");int i1;float f1;std::string s1;tie(i1, f1, s1) = t3;std::cout << "i1 = " << i1 << " f1 = " << f1 << " s1 = " << s1 << std::endl;
5.tuple_size函數 ? 功能是獲取某個 tuple 對象中元素的個數
typedef std::tuple<int, float, std::string> TupleType; // 對tuple<int, float, std::string>取別名 為 TupleTypeint value = std::tuple_size<TupleType>::value;std::cout << "TupleType對象的元素個數為: " << value << std::endl; // 3
6.tuple_element<i, type>::type函數 它只有一個成員變量 type,功能是獲取某個 tuple 對象第 i+1 個元素的類型
std::tuple_element<0, TupleType>::type i2 = 1;std::cout << "i2 = " << i2 << std::endl; // i2 = 1
完整代碼示例:
#include <iostream>
#include <tuple>int main(){std::tuple<int, float, std::string> t1(41, 6.3, "nico");std::cout << "tuple<int, float, std::string>, sizeof = " << sizeof(t1) << std::endl;std::cout << "t1: " << std::get<0>(t1) << ' ' << std::get<1>(t1) << ' ' << std::get<2>(t1) << std::endl; // 獲取下標 0 1 2處的元素// 利用auto關鍵字 自動獲取類型 make_tuple() 函數,它以模板的形式定義在 頭文件中,功能是創建一個 tuple 右值對象(或者臨時對象)auto t2 = std::make_tuple(22, 44, "hello");std::cout << "t2 sizeof = " << sizeof(t2) << std::endl;std::cout << "t2: " << std::get<0>(t2) << ' ' << std::get<1>(t2) << ' ' << std::get<2>(t2) << std::endl;// 比大小操作if(t1 < t2){std::cout << "t1 < t2" << std::endl;}else if(t1 > t2){std::cout << "t1 > t2" << std::endl;}else{std::cout << "t1 = t2" << std::endl;}// tie綁定操作進行復制std::tuple<int, float, std::string> t3(77, 1.1, "more light");int i1;float f1;std::string s1;tie(i1, f1, s1) = t3;std::cout << "i1 = " << i1 << " f1 = " << f1 << " s1 = " << s1 << std::endl;// tuple_size函數 功能是獲取某個 tuple 對象中元素的個數typedef std::tuple<int, float, std::string> TupleType; // 對tuple<int, float, std::string>取別名 為 TupleTypeint value = std::tuple_size<TupleType>::value;std::cout << "TupleType對象的元素個數為: " << value << std::endl; // 3// tuple_element<i, type>::type函數 它只有一個成員變量 type,功能是獲取某個 tuple 對象第 i+1 個元素的類型std::tuple_element<0, TupleType>::type i2 = 1;std::cout << "i2 = " << i2 << std::endl; // i2 = 1return 0;
}
運行結果: