std::tuple类模板的理解与使用

来源:互联网 发布:网络教育一对一策划书 编辑:程序博客网 时间:2024/06/06 10:45

场景

  1. std::pair 可以打包最多两个值到一个类里,常用在需要返回两个值的函数里,因为可以不需要自己定义一个wrapper类,普通集合类肯定不能用,因为C++的集合只能存储泛型的(相同类型)对象. 如果要存储超过2个不同类型的对象, 可以使用 std::tuple, 它能存储最多10个不同对象类型. 是不是发现Java的集合可以存储任意类型强大很多,因为Java对象有共同的根类型,Object.

  2. std::tuple是一个类模板,它能存储固定大小的(10个 vs2010)不同类型对象,它是std::pair的泛化类型.

  3. std::tuple 也可以结合std::tie 来接收函数返回时 unpack 集合里的元素.

参考

std::tuple 
std::tie 
C/C++_操作符重载operator type()和operator()的区别

使用方法

// test_tuple.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <tuple>#include <set>#include <iostream>#include <map>#include <assert.h>#include <string>#include <utility>std::tuple<int, int> f() // this function returns multiple values{    int x = 6;    return std::make_tuple(x, 8); // return {x,7}; in C++17}void TestTuple(){    // heterogeneous tuple construction    int n = 1;    // std::ref 返回一个引用类型包裹,它实现了一个引用类型的 类型转换操作符.    auto t = std::make_tuple(10, "Test", 3.14, std::ref(n), n,10);    // 注意 n 的值已经改变,tuple里的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 返回一个绑定了左值变量的tuple.    std::tie(a, b) = f();    std::cout << a << " " << b << "\n";    std::set<std::string> set_of_str;    bool inserted;    // tuple可以把pair转换为tuple.    std::tie(std::ignore, inserted) = set_of_str.insert("Test");    if (inserted)    {        std::cout << "Value was inserted sucessfully\n";    }}int _tmain(int argc, _TCHAR* argv[]){    TestTuple();    system("pause");    return 0;}
  • 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
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58

输出:

The value of t is (10, Test, 3.14, 7, 1)6 8Value was inserted sucessfully
原创粉丝点击