C++第10课 STL容器 (十)

1.tuple

/*
    可变参模板类
    参数个数、数据类型不限定
*/

void testCreateTuple() 
{
    //正常创建
    tuple<int, string, double, float, int> tup1;
    tuple<int, string, string, double> tup2[3];
    //初始化过程
    tuple<int, string, string, double> mm1 = {14,"小可爱","张三",1.11};
    tuple<int, string> mm2 = make_tuple(9, "小宝贝");
    tuple < string, string >mm3 = forward_as_tuple("小甜心", "卡哇伊");
}
void testVisitTup()
{
    tuple<int, string, string, double> mm1 = { 14,"小可爱","张三",1.11 };
    //直接访问:get<第几个元素(必须是常量值,不能用循环的方式)>(tuple tup);
    cout << get<0>(mm1) << endl;    //输出:14
    //间接访问:tie
    int age;
    string name;
    string vicename;
    double score;
    tie(age, vicename, name, score) = mm1;
    cout << age << vicename << name << score << endl;
    string data;
    tie(ignore, data, ignore, ignore) = mm1;
    cout << data << endl;
}
void testCat()
{
    tuple<string, int> tup = { "小可爱",12 };
    tuple<string, double>tup1 = { "数学",89.0 };

    auto mmInfo = tuple_cat(tup, tup1);
}
//递归方式实现遍历
template <class Tuple, size_t N>
class TuplePrint
{
public:
    static  void print(const Tuple& tup)
    {
        TuplePrint<Tuple, N - 1>::print(tup);
        cout << "\t" << get<N - 1>(tup);
    }
};
//递归终止
template <class Tuple>
class TuplePrint<Tuple, 1>
{
public:
    static void print(const Tuple& tup)
    {
        cout << get<0>(tup);
    }
};
//封装一个统一接口(统一的函数去遍历传入进来元组)
template <class ...Args>
void printTupleData(const tuple<Args...>& tup)
{
    TuplePrint<decltype(tup), sizeof...(Args)>::print(tup);
    cout << endl;
}

void testMyPrint()
{
    tuple<int, string, string, double> mm1 = { 1,"小美","分数",1.11 };
    printTupleData(mm1);
    tuple<int, string> mm2 = make_tuple(2, "小芳");
    printTupleData(mm2);
    tuple<string, string> mm3 = forward_as_tuple("可爱", "美女");
    printTupleData(mm3);
}

 

C++第10课 STL容器 (十)

上一篇:JavaWeb的学习—Filter


下一篇:9.10 python