C++ Tuple::tuple_cat() 函式



C++ 的std::tuple::tuple_cat()函式用於將多個元組連線成單個元組。它接受任意數量的元組作為引數,並返回一個包含所有輸入元組元素的新元組。此函式允許元組的組合,有助於合併或追加元組等操作。

語法

以下是 std::tuple::tuple_cat() 函式的語法。

tuple_cat (Tuples&&... tpls);

引數

  • tpls − 它是一個元組物件的列表,這些元組可以是不同型別的。

返回值

此函式返回一個適當型別的元組物件以容納引數。

示例

在下面的示例中,我們將組合兩個不同型別的元組。

#include <iostream>
#include <tuple>
int main()
{
    std::tuple<int, double> x(1, 0.04);
    std::tuple<char> y('A');
    auto a = std::tuple_cat(x, y);
    std::cout << std::get<0>(a) << "," << std::get<1>(a)<< "," << std::get<2>(a) <<std::endl;
    return 0;
}

輸出

如果執行上述程式碼,它將生成以下輸出:

1,0.04,A

示例

考慮另一種情況,我們將多個元組組合成單個元組。

#include <iostream>
#include <tuple>
int main()
{
    std::tuple<double> x(0.01);
    std::tuple<std::string> y("Welcome");
    std::tuple<bool, int> z(false, 1);
    auto a = std::tuple_cat(x, y, z);
    std::cout << std::get<0>(a) << ", " << std::get<1>(a) << ", "
              << std::get<2>(a) << ", " << std::get<3>(a) <<std::endl;
    return 0;
}

輸出

上述程式碼的輸出如下:

0.01, Welcome, 0, 1

示例

讓我們來看下面的示例,我們將嘗試組合空元組並觀察輸出。

#include <iostream>
#include <tuple>
int main()
{
    std::tuple<> x;
    std::tuple<> y;
    auto a = std::tuple_cat(x, y);
    std::cout << "Size of the combined tuple: " << std::tuple_size<decltype(a)>::value << std::endl;
    return 0;
}

輸出

上述程式碼的輸出如下:

Size of the combined tuple: 0

示例

以下示例將結合使用 make_tuple() 函式和 tuple_cat() 函式。

#include <iostream>
#include <tuple>
int main()
{
    auto x = std::make_tuple(1, 0.01);
    auto y = std::make_tuple("TutorialsPoint", 'R');
    auto a = std::tuple_cat(x, y);
    std::cout << std::get<0>(a) << ", " << std::get<1>(a) << ", "
              << std::get<2>(a) << ", " << std::get<3>(a) << std::endl;
    return 0;
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

1, 0.01, TutorialsPoint, R
廣告