[③C++ Boost]: boost::tuple使用

tuple即元组,它定义了一个有固定数目元素的容器,其中每个元素类型可以不相同,这点它与其他类型的容器不同,例如vector和array(它们所包含的元素类型必须是一样的)。

当一个函数有许多返回值时,为了可读性,一般可以用class或者struct来封装要返回的多个值。boost::tuple提供了另外一种解决函数返回多值得方法,优点是不增加代码量,std::pair其实就是boost::tuple的2个参数的特例,对boost::tuple来说可以绑定更多的参数。

  • 添加头文件:
cpp 复制代码
#include <boost/tuple/tuple.hpp>
  • 构造tuple,构造的参数不必与元素的类型精确相同,只要它们可以隐式地转换就可以了:
cpp 复制代码
boost::tuple<int,double,std::string> my_tuple(42, 3.14, "My first tuple!");
  • make_tuple,生成tuple, 有助于自动推导元组类型,缺省情况下,make_tuple设置元素类型为非const,
    非引用的。为了使一个tuple的元素设为引用类型或者const类型,需要使用boost::ref和boost::cref:
cpp 复制代码
int plain = 42;
boost::make_tuple(plain);

int& ref = plain;
boost::make_tuple(boost::ref(ref));

const int& cref = ref;
boost::make_tuple(boost::cref(cref));
  • 访问tuple元素,t.get()或get(t) ,取得第N个元素值:
cpp 复制代码
#include <iostream>
#include <string>
#include "boost/tuple/tuple.hpp"

int main() {
  boost::tuple<int,double,std::string> my_tuple(42, 3.14, "My first tuple!"); 

  int i = boost::tuples::get<0>(my_tuple);
  double d = my_tuple.get<1>();
  std::string s = boost::get<2>(my_tuple);
}
相关推荐
郝学胜-神的一滴1 小时前
中级OpenGL教程 023:Assimp模型加载全解——从源码到架构的骈文探秘
c++·unity·游戏引擎·cmake·unreal engine·opengl
星恒随风1 小时前
C++ STL 详解:list 的使用、迭代器失效、模拟实现与 vector 对比
开发语言·数据结构·c++·笔记·学习·list
牢姐与蒯1 小时前
c++之异常
开发语言·c++·c++11
此生决int1 小时前
深入理解C++系列(02)——类和对象(上)
开发语言·c++
red_redemption2 小时前
自由学习记录(208)
学习
一起努力啊~2 小时前
DataWhale组队学习笔记--llm-algo-leetcode(五)
笔记·学习·llm
zjun10013 小时前
C++:单例模式
c++·单例模式
世人万千丶10 小时前
鸿蒙Flutter Flex多子组件权重分配
学习·flutter·华为·harmonyos·鸿蒙
同勉共进11 小时前
记一例 vibe coding + gcc bug 导致的线程池死锁问题
c++·线程池·gcc·死锁·vibe coding
我叫洋洋12 小时前
C ++ [ hello world ]
c语言·c++·算法