C++11新特性std::make_tuple的使用
#代码知识 发布时间: 2026-01-12
std::tuple是C++ 11中引入的一个非常有用的结构,以前我们要返回一个包含不同数据类型的返回值,一般都需要自定义一个结构体或者通过函数的参数来返回,现在std::tuple就可以帮我们搞定。

1.引用头文件
#include <tuple>
2. Tuple初始化
std::tuple的初始化可以通过构造函数实现。
// Creating and Initializing a tuple
std::tuple<int, double, std::string> result1 { 22, 19.28, "text" };
这种初始化方式要定义各个元素的数据类型,比较繁琐,C++11也提供了另外一种方式std::make_tuple。
3. std::make_tuple
// Creating a tuple using std::make_tuple auto result2 = std::make_tuple( 7, 9.8, "text" );
这种初始化方式避免需要逐个指定元素类型的问题,自动化实现各个元素类型的推导。
完整例子一:
#include <iostream>
#include <tuple>
#include <string>
int main()
{
// Creating and Initializing a tuple
std::tuple<int, double, std::string> result1 { 22, 19.28, "text" };
// Compile error, as no way to deduce the types of elements in tuple
//auto result { 22, 19.28, "text" }; // Compile error
// Creating a tuple using std::make_tuple
auto result2 = std::make_tuple( 7, 9.8, "text" );
// std::make_tuple automatically deduced the type and created tuple
// Print values
std::cout << "int value = " << std::get < 0 > (result2) << std::endl;
std::cout << "double value = " << std::get < 1 > (result2) << std::endl;
std::cout << "string value = " << std::get < 2 > (result2) << std::endl;
return 0;
}
输出:
<strong>int</strong> value = 7
<strong>double</strong> value = 9.8
string value = text
完整例子二:
#include <iostream>
#include <tuple>
#include <functional>
std::tuple<int, int> f() // this function returns multiple values
{
int x = 5;
return std::make_tuple(x, 7); // return {x,7}; in C++17
}
int main()
{
// heterogeneous tuple construction
int n = 1;
auto t = std::make_tuple(10, "Test", 3.14, std::ref(n), n);
n = 7;
std::cout << "The value of t is " << "("
<< std::get<0>(t) << ", " << std::get<1>(t) << ", "
<< std::get<2>(t) << ", " << std::get<3>(t) << ", "
<< std::get<4>(t) << ")\n";
// function returning multiple values
int a, b;
std::tie(a, b) = f();
std::cout << a << " " << b << "\n";
}
输出:
The value of t is (10, Test, 3.14, 7, 1)
5 7
参考材料
https://thispointer.com/c11-make_tuple-tutorial-example/
https://en.cppreference.com/w/cpp/utility/tuple/make_tuple
上一篇 : C++11新特性std::tuple的使用方法
下一篇 : 在.NET中使用DiagnosticSource的方法
-
SEO外包最佳选择国内专业的白帽SEO机构,熟知搜索算法,各行业企业站优化策略!
SEO公司
-
可定制SEO优化套餐基于整站优化与品牌搜索展现,定制个性化营销推广方案!
SEO套餐
-
SEO入门教程多年积累SEO实战案例,从新手到专家,从入门到精通,海量的SEO学习资料!
SEO教程
-
SEO项目资源高质量SEO项目资源,稀缺性外链,优质文案代写,老域名提权,云主机相关配置折扣!
SEO资源
-
SEO快速建站快速搭建符合搜索引擎友好的企业网站,协助备案,域名选择,服务器配置等相关服务!
SEO建站
-
快速搜索引擎优化建议没有任何SEO机构,可以承诺搜索引擎排名的具体位置,如果有,那么请您多注意!专业的SEO机构,一般情况下只能确保目标关键词进入到首页或者前几页,如果您有相关问题,欢迎咨询!