系统城装机大师 - 固镇县祥瑞电脑科技销售部宣传站!

当前位置:首页 > 网络编程 > 其它综合 > 详细页面

C++11新特性std::make_tuple的使用

时间:2020-10-06来源:www.pcxitongcheng.com作者:电脑系统城

std::tuple是C++ 11中引入的一个非常有用的结构,以前我们要返回一个包含不同数据类型的返回值,一般都需要自定义一个结构体或者通过函数的参数来返回,现在std::tuple就可以帮我们搞定。

1.引用头文件

?
1 #include <tuple>

2. Tuple初始化

std::tuple的初始化可以通过构造函数实现。

?
1
2
// 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

?
1
2
// Creating a tuple using std::make_tuple
auto result2 = std::make_tuple( 7, 9.8, "text" );

这种初始化方式避免需要逐个指定元素类型的问题,自动化实现各个元素类型的推导。

完整例子一:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#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

完整例子二:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#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

参考材料

到此这篇关于C++11新特性std::make_tuple的使用的文章就介绍到这了,更多相关C++11 std::make_tuple内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

分享到:

相关信息

  • C++ AVLTree高度平衡的二叉搜索树深入分析

    一、AVL树的概念 二、AVL树节点的定义 三、AVL树的插入 四、AVL树的旋转 1.左单旋 2.右单旋 3.左右双旋 4.右左双旋 五、进行验证 六、AVLTree的性能...

    2023-03-09

  • idea构建web项目的超级详细教程

    1、idea构建web项目 1、新建一个空项目 2、新建java模块,名为webDemo1 3、选择webDemo1右键,选择Add Framework Support 4、在WEB-INF下新建文件夹classes和lib 5、打开项目结构(Project Structure) 6、项目配置 7、模...

    2023-03-09

系统教程栏目

栏目热门教程

人气教程排行

站长推荐

热门系统下载