Tuples in C++(元组)

本文主要介绍了 C++ 中元组的相关知识。元组可容纳不同类型元素,文中阐述了元组的基本操作,如使用三个核心函数获取、构造和拆包元组,还介绍了其他参数,如返回元素数、解压缩元组值等,最后说明了元组合并与遍历的实现方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

什么是元组?

元组是一个可以容纳许多元素的对象。元素可以是不同的数据类型。元组的元素被初始化为参数,以便访问它们。纵观传统 C++ 中的容器,除了 std::pair 外,似乎没有现成的结构能够用来存放不同类型的数据(通常我们会自己定义结构)。但 std::pair 的缺陷是显而易见的,只能保存两个元素。

元组基本操作

关于元组的使用有三个核心的函数:

  1. std::get: 获得元组某个位置的值 ,用于访问元组值并修改它们,它接受索引和元组名称作为参数来访问特定的元组元素,C++14 增加了使用类型来获取元组中的对象。
  2. std::make_tuple: 构造元组,用于为元组赋值。传递的值应与元组中声明的值一致。
  3. std::tie: 元组拆包
#include <iostream>  
#include <tuple>
#include <string>

auto get_student(int id)
{
	// 返回类型被推断为 std::tuple<double, char, std::string>

	if (id == 0)
		return std::make_tuple(3.8, 'A', "张三");
	if (id == 1)
		return std::make_tuple(2.9, 'C', "李四");
	if (id == 2)
		return std::make_tuple(1.7, 'D', "王五");
	return 
		std::make_tuple(0.0, 'D', "null");	// 如果只写 0 会出现推断错误, 编译失败
}

int main()
{
	auto student = get_student(0);
	std::cout << "ID: 0, "
		<< "GPA: "  << std::get<0>(student) << ", "
		<< "成绩: " << std::get<1>(student) << ", "
		<< "姓名: " << std::get<2>(student) << '\n';

	double gpa;
	char grade;
	std::string name;

	// 元组进行拆包
	std::tie(gpa, grade, name) = get_student(1);
	std::cout << "ID: 1, "
		<< "GPA: "  << gpa << ", "
		<< "成绩: " << grade << ", "
		<< "姓名: " << name << '\n';

	//C++14 std::get增加了使用类型来获取元组中的对象:
        std::tuple<std::string, double, double, int> t("123", 4.5, 6.7, 8);
	std::cout << std::get<std::string>(t) << std::endl;
	//std::cout << std::get<double>(t) << std::endl;   // 非法, 引发编译期错误
	std::cout << std::get<3>(t) << std::endl;

}

 

其他参数

  • tuple_size:返回元组中存在的元素数。
//C++ code to demonstrate tuple_size 
#include<iostream> 
#include<tuple> // for tuple_size and tuple 
using namespace std; 
int main() 
{ 
  
    // Initializing tuple 
    tuple <char,int,float> geek(20,'g',17.5); 
  
    // Use of size to find tuple_size of tuple 
    cout << "The size of tuple is : "; 
    cout << tuple_size<decltype(geek)>::value << endl; 
  
    return 0; 
} 

输出:

The size of tuple is : 3

  • tie( )

tie( )的工作是将元组值解压缩为单独的变量。tie( )有两种变体,with 和 without “ignore”, “ignore”忽略特定的元组元素并阻止它被解压缩。

#include<iostream> 
#include<tuple> // for tie() and tuple 
using namespace std; 
int main() 
{    
    // Initializing variables for unpacking 
    int i_val; 
    char ch_val; 
    float f_val;    
      
    // Initializing tuple 
    tuple <int,char,float> tup1(20,'g',17.5); 
  
    // Use of tie() without ignore 
    tie(i_val,ch_val,f_val) = tup1; 
      
    // Displaying unpacked tuple elements 
    // without ignore 
    cout << "The unpacked tuple values (without ignore) are : "; 
    cout << i_val << " " << ch_val << " " << f_val; 
    cout << endl; 
      
    // Use of tie() with ignore 
    // ignores char value 
    tie(i_val,ignore,f_val) = tup1; 
      
    // Displaying unpacked tuple elements 
    // with ignore 
    cout << "The unpacked tuple values (with ignore) are : "; 
    cout << i_val  << " " << f_val; 
    cout << endl; 
  
    return 0; 
  
} 
  •  tuple_cat()

此函数连接两个元组并返回一个新元组。

// C++ code to demonstrate working of tuple_cat() 
#include<iostream> 
#include<tuple> // for tuple_cat() and tuple 
using namespace std; 
int main() 
{ 
    // Initializing 1st tuple 
    tuple <int,char,float> tup1(20,'g',17.5); 
  
    // Initializing 2nd tuple 
    tuple <int,char,float> tup2(30,'f',10.5); 
      
    // Concatenating 2 tuples to return a new tuple 
    auto tup3 = tuple_cat(tup1,tup2); 
      
    // Displaying new tuple elements 
    cout << "The new tuple elements in order are : "; 
    cout << get<0>(tup3) << " " << get<1>(tup3) << " "; 
    cout << get<2>(tup3) << " " << get<3>(tup3) << " "; 
    cout << get<4>(tup3) << " " << get<5>(tup3) << endl; 
  
    return 0; 
} 

输出: 

The new tuple elements in order are : 20 g 17.5 30 f 10.5

  • std::variant 

运行期索引

第一个例子中有这么一个片段:

 std::cout << "ID: 0, "
    << "GPA: " << std::get<0>(student) << ", "
    << "成绩: " << std::get<1>(student) << ", "
    << "姓名: " << std::get<2>(student) << '\n';

如果你仔细思考一下可能就会发现上面代码的问题,std::get<> 依赖一个编译期的常量,所以下面的方式是不合法的:

int index = 1;
std::get<index>(t);

 那么要怎么处理?答案是,标准库做不到。这里介绍一个使用 boost::variant 配合变长模板参数的黑魔法:

提示:使用 boost 只是暂时性的解决方案,variant 已在 C++17 中被纳入标准库 std::variant,见扩展主题它的讨论。http://en.cppreference.com/w/cpp/utility/variant

#include <boost/variant.hpp>
template <size_t n, typename... T>
boost::variant<T...> _tuple_index(size_t i, const std::tuple<T...>& tpl) {
    if (i == n)
        return std::get<n>(tpl);
    else if (n == sizeof...(T) - 1)
        throw std::out_of_range("越界.");
    else
        return _tuple_index<(n < sizeof...(T)-1 ? n+1 : 0)>(i, tpl);
}
template <typename... T>
boost::variant<T...> tuple_index(size_t i, const std::tuple<T...>& tpl) {
    return _tuple_index<0>(i, tpl);
}

这样我们就能:

int i = 1;
std::cout << tuple_index(i, t) << std::endl;

 

实现元组合并与遍历

如何快速遍历一个元组?但是我们刚才介绍了如何在运行期通过非常数索引一个 tuple 那么遍历就变得简单了,首先我们需要知道一个元组的长度,可以:

template <typename T>
auto tuple_len(T &tpl) {
    return std::tuple_size<T>::value;
}

这样就能够对元组进行迭代了:

// 迭代
for(int i = 0; i != tuple_len(new_tuple); ++i)
    // 运行期索引
    std::cout << tuple_index(i, new_tuple) << std::endl;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值