欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2020年10月06日 09:35:05   作者:半杯茶的小酒杯  
這篇文章主要介紹了C++11新特性std::make_tuple的使用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

std::tuple是C++ 11中引入的一個(gè)非常有用的結(jié)構(gòu),以前我們要返回一個(gè)包含不同數(shù)據(jù)類型的返回值,一般都需要自定義一個(gè)結(jié)構(gòu)體或者通過(guò)函數(shù)的參數(shù)來(lái)返回,現(xiàn)在std::tuple就可以幫我們搞定。

1.引用頭文件

#include <tuple>

2. Tuple初始化

std::tuple的初始化可以通過(guò)構(gòu)造函數(shù)實(shí)現(xiàn)。

// Creating and Initializing a tuple
std::tuple<int, double, std::string> result1 { 22, 19.28, "text" };

這種初始化方式要定義各個(gè)元素的數(shù)據(jù)類型,比較繁瑣,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" );

這種初始化方式避免需要逐個(gè)指定元素類型的問(wèn)題,自動(dòng)化實(shí)現(xiàn)各個(gè)元素類型的推導(dǎo)。

完整例子一:

#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

到此這篇關(guān)于C++11新特性std::make_tuple的使用的文章就介紹到這了,更多相關(guān)C++11 std::make_tuple內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論