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
广告

© . All rights reserved.