std::tuple 是一個固定大小、異質型別的容器,可攜帶多個不同型別的值。常用於函式回傳多個值,或暫時組合不相關資料。特點:快速、低開銷、無結構化介面。
std::tuple<int, double, std::string> t(64, 128.0, "Caroline");std::make_tuple:auto t2 = std::make_tuple("Caroline", "Wendy", 1992);使用 std::get<索引>(tuple),索引必須為編譯期常數(常數運算式)。
std::tuple_size<decltype(t)>::valuestd::tuple_element<N, decltype(t)>::type兩個 tuple 型別元素數量相同且對應位置可比較(如 int 與 double),即可使用 <, >, == 等運算子,按字典序比較。
因 std::get 索引必須為常數,無法在迴圈中用變數索引。若需迭代,可考慮結構化綁定(C++17)或手寫遞迴模板。
/* CppPrimer.cpp
* Created on: 2013.12.9
* Author: Caroline
*/
#include <iostream>
#include <vector>
#include <string>
#include <tuple>
using namespace std;
std::tuple<std::string, int> giveName() {
std::string cw("Caroline");
int a(2013);
return std::make_tuple(cw, a);
}
int main() {
std::tuple<int, double, std::string> t(64, 128.0, "Caroline");
std::tuple<std::string, std::string, int> t2 =
std::make_tuple("Caroline", "Wendy", 1992);
size_t num = std::tuple_size<decltype(t)>::value;
std::cout << "num = " << num << std::endl;
std::tuple_element<1, decltype(t)>::type cnt = std::get<1>(t);
std::cout << "cnt = " << cnt << std::endl;
std::tuple<int, int> ti(24, 48);
std::tuple<double, double> td(28.0, 56.0);
bool b = (ti < td);
std::cout << "b = " << b << std::endl;
auto a = giveName();
std::cout << "name: " << get<0>(a)
<< " years: " << get<1>(a) << std::endl;
return 0;
}
num = 3
cnt = 128
b = 1
name: Caroline years: 2013
tuple 適合短暫、小規模的異質資料組合。若需語意清晰、可擴充的資料結構,建議改用 struct 或 class。