C++ Tuple::get() 函式



C++ 的 std::tuple::get() 函式允許您透過索引訪問儲存在元組中的元素。它將元組和索引作為引數,並返回該索引處的值。索引必須在編譯時已知,並且必須在元組的範圍內。例如,std::get<0>(mytuple) 檢索第一個元素。

當我們嘗試訪問超出範圍的索引時,會導致執行時錯誤。

語法

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

typename tuple_element< I, tuple<Types...> >::type& get(tuple<Types...>& tpl) noexcept;

引數

  • I - 表示元素的位置。
  • Types - 表示元素的型別。
  • tpl - 表示包含超過 I 個元素的元組物件。

返回值

此函式返回對元組 tpl 的第 I 個元素的引用。

示例

讓我們看下面的例子,我們將訪問元組的第一個元素。

#include <iostream>
#include <tuple>
int main()
{
    std::tuple<int, float, std::string> x(1, 0.04, "Welcome");
    int firstElement = std::get<0>(x);
    std::cout << " " << firstElement << std::endl;
    return 0;
}

輸出

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

1

示例

考慮另一種情況,我們將訪問元組的第三個元素。

#include <iostream>
#include <tuple>
int main()
{
    std::tuple<int, float, std::string> x(10, 3.14, "TutorialsPoint");
    std::string thirdElement = std::get<2>(x);
    std::cout << " " << thirdElement << std::endl;
    return 0;
}

輸出

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

TutorialsPoint

示例

在下面的示例中,我們將使用 std::tie 從元組中提取多個元素。

#include <iostream>
#include <tuple>
int main()
{
    std::tuple<int, float, std::string> x(1, 0.04, "TP");
    int first;
    float second;
    std::tie(first, second, std::ignore) = x;
    std::cout << "1st Element: " << first << ", 2nd Element: " << second << std::endl;
    return 0;
}

輸出

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

1st Element: 1, 2nd Element: 0.04

示例

下面的示例中,我們將使用 get() 函式並修改元組。

#include <iostream>
#include <tuple>
int main()
{
    std::tuple<int, std::string, double> x(1, "TP", 0.02);
    std::get<1>(x) = "TutorialsPoint";
    std::cout << "After Modification: " << std::get<0>(x) << ", " << std::get<1>(x) << ", " << std::get<2>(x) << std::endl;
    return 0;
}

輸出

以上程式碼的輸出如下:

After Modification: 1, TutorialsPoint, 0.02
廣告