std::tuple可存储多类型值并实现多值返回,通过make_tuple创建,get或结构化绑定解包,c++17支持更直观的解包方式。

在C++中,std::tuple 是一个能存储多个不同类型值的容器,常用于函数返回多个值的场景。它定义在 <tuple> 头文件中,是实现“多值返回”的简洁方式之一。
创建和初始化 tuple
你可以使用 std::make_tuple、直接构造或 std::tie 来创建 tuple。
示例:
#include <tuple> #include <iostream> // 创建 tuple auto t1 = std::make_tuple(10, 3.14, "hello"); std::tuple<int, double, std::string> t2(42, 2.71, "world");
从函数返回多个值
tuple 最常见的用途是让函数返回多个结果,替代结构体或输出参数。
立即进入“豆包AI人工智官网入口”;
立即学习“豆包AI人工智能在线问答入口”;
std::tuple<int, int, double> divideWithRemainder(int a, int b) { if (b == 0) return {0, 0, 0.0}; int quotient = a / b; int remainder = a % b; double ratio = static_cast<double>(a) / b; return std::make_tuple(quotient, remainder, ratio); }
调用这个函数并获取结果:
auto result = divideWithRemainder(10, 3); int q = std::get<0>(result); // 商 int r = std::get<1>(result); // 余数 double d = std::get<2>(result); // 比值
解包 tuple:结构化绑定(C++17)
C++17 引入了结构化绑定,可以更优雅地“解包”tuple。
auto [quotient, remainder, ratio] = divideWithRemainder(10, 3); std::cout << "商: " << quotient << ", 余数: " << remainder << ", 比值: " << ratio << "n";
变量名可读性强,代码更清晰。
使用 std::tie 解包(C++11/14)
在不支持 C++17 的环境中,可用 std::tie 接收 tuple 值。
int q, r; double d; std::tie(q, r, d) = divideWithRemainder(10, 3);
如果不想接收某个值,可以用 std::ignore:
std::tie(q, std::ignore, d) = divideWithRemainder(10, 3); // 忽略余数
基本上就这些。tuple 简洁实用,配合结构化绑定,多值返回变得非常自然。不复杂但容易忽略细节,比如类型顺序和 get 的索引匹配。


