C++ Tuple::make_tuple() 函式



C++ 的std::tuple::make_tuple() 函式用於建立元組,元組是固定大小的元素集合。它接受任何型別的引數,並構建一個包含這些元素的元組。它透過減少其引數的型別來簡化元組的建立。

例如,std::make_tuple(1, "TP", 0.01) 建立一個包含整數、字串和浮點數的元組。

語法

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

make_tuple(Args&&... args);

引數

  • args - 表示要儲存在元組中的值。

返回值

此函式返回一個使用提供的引數構造的元組物件。

示例

在下面的示例中,我們將構造一個不同資料型別的元組。

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

輸出

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

1, TutorialsPoint, 0.01

示例

考慮另一種情況,我們將使用變數構造元組。

#include <iostream>
#include <tuple>
int main()
{
    int x = 1;
    std::string y = "Welcome";
    auto myTuple = std::make_tuple(x, y);
    std::cout << " " << std::get<0>(myTuple) << ", "<< std::get<1>(myTuple) << " " <<std::endl;
    return 0;
}

輸出

如果我們執行上面的程式碼,它將生成以下輸出:

1, Welcome 

示例

讓我們看看下面的示例,我們將使用 make_tuple() 函式建立一個包含指向現有變數的指標的元組。

#include <iostream>
#include <tuple>
using namespace std;
int main()
{
    int x = 20;
    double y = 0.01;
    auto a = make_tuple(&x, &y);
    x = 1;
    cout << *(get<0>(a)) << ", " << *(get<1>(a)) <<endl;
    return 0;
}

輸出

以下是上面程式碼的輸出:

1, 0.01

示例

以下是 make_tuple() 函式建立包含巢狀元組的元組的示例。

#include <iostream>
#include <tuple>
using namespace std;
int main()
{
    auto x = make_tuple(0, make_tuple(1, 2), 3);
    cout << get<0>(x) << ", " << get<1>(get<1>(x)) << ", " << get<2>(x) << endl;
    return 0;
}

輸出

上面程式碼的輸出如下:

0, 2, 3
廣告