使用 Tuple 和 Pair 在 C++ 中从函数返回多个值

2024年8月28日 | 阅读 4 分钟

我们可能遇到过这样的场景:在处理函数时,其返回类型只能是单一数据类型,但我们却需要返回多种数据类型。为了解决这个问题,我们将学习在 C++ 中使用 Tuple 和 Pair 从函数返回多个值的概念。

C++ 中的 Tuple 和 Pair

它是一个持有任何数据类型的单元或元素的对象。在 C++ 编程语言中,Tuple 数据类型类 std::tuple 的大小是固定的。C++ 中的 Pair 是

用于演示 Tuple 的 C++ 代码

输出

values of the Tuple during the initial stage are as follows: z 20 85.5
values of the Tuple after the modification stage are as follows: b 20 20.5

用于演示 Pair 的 C++ 代码

输出

41 62
63 62
103 44 n

使用 Tuple 和 Pair 从函数返回多个值的 C++ 代码。

输出

The values returned by the Tuple are as follows: 110 15 a
The values returned by the Pair are as follows: 32 25