一、元組std::tuple
傳統C++中的容器,除了std::pair外,沒有現成的數據結構能用來存放不同類型的數據,但是std::pair的缺陷是隻能保存;兩個元素。
二、元組基本操作
元組的使用有三個核心的函數:
- std::make_tuple:構造元組
- std::get:獲得元組某個位置的值
- std::tie:元組拆包
//在C++14下運行
#include <tuple>
#include <iostream>
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';
}
std::get除了使用常量獲取元組對象外,C++14增加了使用類型來獲取元組中的對象:
#include <tuple>
#include <iostream>
int main()
{
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<2>(t) << std::endl;
}
結果:
123
6.7
三、運行期索引
std::get<> 依賴一個編譯期的常量,所以下面的方式是不合法的:
int index = 1;
std::get<index>(t);
處理方式:
//C++17
#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;
四、元組合並與遍歷
通過 std::tuple_cat 來實現:
auto new_tuple = std::tuple_cat(get_student(1), std::move(t));
馬上就能夠發現,應該如何快速遍歷一個元組?但是剛纔介紹瞭如何在運行期通過非常數索引一個 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;