C++标准库之 Tuple

31 阅读1分钟

tuple 元组 是与 pair 相似的容器,只不过 pair 容器的大小是固定的两个,但是 tuple 的容量是不固定的,

先来看看 tuple 的这个class 的信息

template<typename...>
class tuple;

从这个类中可以看出来,在声明 tuple 时指定的数据类型长度是不固定的,而且还由于使用的是模板类型,所以 tuple 的类型可以是任何类型的组合

创建 tuple

using namespace std;

int main() {
    //正常写法
    tuple<string,int,int>  t("tsm",10,5);
    //简写 ,不用指定类型
    auto t1=make_tuple(1,"sfds",1.2f,5L);

    return 0;
}

获取 tuple 元组的size

using namespace std;

int main() {

    //正常写法
    tuple<string,int,int>  t("tsm",10,5);

    //简写 ,不用指定类型
    auto t1=make_tuple(1,"sfds",1.2f,5L);

    //获取 tuple 的size
    cout<< "元组 t 的 size::" << tuple_size<decltype(t)>::value <<endl;
    

    return 0;
}

结果 --> 3

获取 tuple 元组中的第 i 个数据

using namespace std;

int main() {


   tuple<string,int,int>  t("tsm",10,5);

   // 获取元组中的第 i 个数据
   auto item1= std::get<0>(t);
   
   cout << item1 << endl;


   return 0;
}

拼接 tuple

using namespace std;

int main() {


    tuple<string,int,int>  t("tsm",10,5);



    auto t1=make_tuple(1,"str",10);

    auto res= tuple_cat(t,t1);


    cout<<  get<0>(res)<<endl;
    cout<<  get<1>(res)<<endl;
    cout<<  get<2>(res)<<endl;
    cout<<  get<3>(res)<<endl;
    cout<<  get<4>(res)<<endl;
    cout<<  get<5>(res)<<endl;

    return 0;
}

结果

tsm
10
5
1
str
10

在这里我想使用 for 遍历 拼接后的 tuple 但是发现 get(res) 这种写法是不被允许的,