什么是元组?
元组是一个可以容纳许多元素的对象。元素可以是不同的数据类型。元组的元素被初始化为参数,以便访问它们。纵观传统 C++ 中的容器,除了 std::pair
外,似乎没有现成的结构能够用来存放不同类型的数据(通常我们会自己定义结构)。但 std::pair
的缺陷是显而易见的,只能保存两个元素。
元组基本操作
关于元组的使用有三个核心的函数:
std::get
: 获得元组某个位置的值 ,用于访问元组值并修改它们,它接受索引和元组名称作为参数来访问特定的元组元素,C++14 增加了使用类型来获取元组中的对象。std::make_tuple
: 构造元组,用于为元组赋值。传递的值应与元组中声明的值一致。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;