C++11, 14, 17對tuple元素的訪問詳情
C++11, 14, 17對tuple元素的訪問
std::tuple 作為可以存放任意個數(shù),任意類型的元祖被我個人經(jīng)常使用。
記得以前看侯捷談到這個數(shù)據(jù)結(jié)構(gòu)的時候,被他的實現(xiàn)所驚奇,太巧妙地設(shè)計。
我自己在使用std::tuple的時候也隨著C++版本的更新嘗試新的寫法,對于元組中元素的獲取,我一直覺得很有意思:
比如我有這么一個源文件:
#include <iostream> #include <tuple> #define CPP11 (__cplusplus < 201401L) #define CPP14 (__cplusplus < 201701L and __cplusplus > 201401L) #define CPP17 (__cplusplus >= 201702L) class Moo { Moo() { ::printf("%s\n", __PRETTY_FUNCTION__); } Moo(Moo const &) { ::printf("%s\n", __PRETTY_FUNCTION__); } Moo(Moo &&) { ::printf("%s\n", __PRETTY_FUNCTION__); } Moo &operator=(Moo const &) noexcept { ::printf("%s\n", __PRETTY_FUNCTION__); return *this; } Moo &operator=(Moo &&) noexcept { ::printf("%s\n", __PRETTY_FUNCTION__); return *this; } ~Moo() { ::printf("%s\n", __PRETTY_FUNCTION__); } }; int main() { std::cout << "c++ version:" << __cplusplus << std::endl; auto &&tp = std::make_tuple<Moo, const char *, int>(Moo(), "hello world", 3); #if CPP11 auto &&first = std::get<0>(tp); auto &&second = std::get<1>(tp); auto &&third = std::get<2>(tp); #endif #if CPP14 auto &&first = std::get<Moo>(tp); auto &&second = std::get<const char *>(tp); auto &&third = std::get<int>(tp); #endif #if CPP17 auto [a, b, c] = tp; auto &[first, second, third] = tp; #endif return 0; }
Moo類考察當(dāng)前對象在構(gòu)造tuple和返回值的過程中經(jīng)歷怎樣的人生
- C++11: 使用std::get方法來獲取對應(yīng)秩的元素的引用
- C++14: 使用類似在nlohmannjson里面獲取對應(yīng)類型的json對象的方式,通過類型來獲取對應(yīng)的元素的引用,有點現(xiàn)代C++那味兒了吼
- C++17: 引入了結(jié)構(gòu)化綁定,不實用引用的時候會返回新創(chuàng)建的臨時對象,a, b, c是對臨時對象的右值引用,而使用引用則是想std::get那樣引用原本對象。C++17結(jié)構(gòu)化綁定yyds!表達(dá)力比之前強(qiáng)太多
std::tuple大總結(jié)
C++11引入了一個新的較實用的模板類型,std::tuple,也即是元組。元組是一個固定大小的不同類型(異質(zhì),heterogeneous)值的集合,也即它可以同時存放不同類型的數(shù)據(jù)。
類似于python中用小括號表示的元組類型。C++已有的std::pair類型類似于一個二元組,可看作是std::tuple的一個特例,std::tuple也可看作是std::pair的泛化。std::pair的長度限制為2,而std::tuple的元素個數(shù)為0~任意個。
元組的使用
- 有時候希望將一些數(shù)據(jù)組合成單一對象,但又不想麻煩地定義一個新數(shù)據(jù)結(jié)構(gòu)來表示這些數(shù)據(jù)時,std::tuple是非常有用的。我們可以將std::tuple看作一個“快速而隨意”的數(shù)據(jù)結(jié)構(gòu)。我們可以把它當(dāng)作一個通用的結(jié)構(gòu)體使用,但又不需要創(chuàng)建和獲取結(jié)構(gòu)體的特征,使得程序更加簡潔直觀。
- 創(chuàng)建一個std::tuple對象時,可以使用tuple的默認(rèn)構(gòu)造函數(shù),它會對每個成員進(jìn)行值初始化;也可以為每個成員提供一個初始值,此時的構(gòu)造函數(shù)是explicit的,因此必須使用直接初始化方法。
- 一個std::tuple類型的成員數(shù)目是沒有限制的,因此,元組的成員都是未命名的。要訪問一個元組的成員,就要使用一個名為get的標(biāo)準(zhǔn)庫函數(shù)模板。為了使用get,我們必須指定一個顯式模板實參,它指出我們想要訪問第幾個成員。我們傳遞給get一個tuple對象,它返回指定成員的引用。get尖括號中的值必須是一個整型常量表達(dá)式。與往常一樣,我們從0開始計數(shù),意味著get<0>是第一個成員。
- 為了使用tuple_size或tuple_element,我們需要知道一個元組對象的類型。與往常一樣,確定一個對象的類型的最簡單方法就是使用decltype。
- std::tuple的一個常見用途是從一個函數(shù)返回多個值。
- std::tuple中元素是被緊密地存儲的(位于連續(xù)的內(nèi)存區(qū)域),而不是鏈?zhǔn)浇Y(jié)構(gòu)。
- std::tuple實現(xiàn)了多元組,這是一個編譯期就確定大小的容器,可以容納不同類型的元素。多元組類型在當(dāng)前標(biāo)準(zhǔn)庫中被定義為可以用任意數(shù)量參數(shù)初始化的類模板。每一模板參數(shù)確定多元組中一元素的類型。所以,多元組是一個多類型、大小固定的值的集合。
典型使用
創(chuàng)建和初始化
{ ? ? std::tuple<int, double, std::string> first; ? ?// 創(chuàng)建一個空的元組,需要指定元組元素的數(shù)據(jù)類型,調(diào)用各個成員的默認(rèn)構(gòu)造函數(shù)進(jìn)行初始化。 ? ? std::tuple<int, double, std::string> second(first); ?// 拷貝構(gòu)造 ? ? std::tuple<int, char> third(10, 'a'); ? ? ? ?// 創(chuàng)建并初始化,使用小括號初始化 ? ? std::tuple<int, std::string, double> fourth{42, "Test", -3.14}; ?// 創(chuàng)建并初始化,使用新的大括號初始化列表方式初始化 ? ? std::tuple<int, char> fifth(std::make_tuple(20, 'b')); ? ? // 移動構(gòu)造,使用模板庫的make_tuple ? ? first = std::make_tuple(1, 3.14, "tuple"); ? ? ? // 移動賦值 ? ? int i_third = 3; ? ? std::tuple<int&> sixth(std::ref(i_third)); ? // 創(chuàng)建一個元組,元組的元素可以被引用 }?
元組的訪問和修改
std::get<N>() { ? ? int n = 1; ? ? auto t = std::make_tuple(10, "Test", 3.14, std::ref(n), n); ? ? // get尖括號中的值必須是一個整型常量表達(dá)式。從0開始計數(shù),意味著get<0>是第一個成員。 ? ? 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"; ? ? // 由于get返回指定元素的引用,所以可用來修改指定位置的元素的值。此處因為第4個元素是引用類型,所以被引用的值也會改變 ? ? std::get<3>(t) = 9; ? ? std::cout << n << std::endl; }
元組的元素個數(shù)
使用std::tuple_size<>()
{ ? ? std::tuple<char, int, long, std::string> first('A', 2, 3, "4"); ? ? int i_count = std::tuple_size<decltype(first)>::value; ?// 使用std::tuple_size計算元組個數(shù) ? ? std::cout << "the number of elements of a tuple:" << i_count << "\n"; }
元組的解包
std::tie() 元組包含一個或者多個元素,使用std::tie解包: 首先需要定義對應(yīng)元素的變量,再使用tie。
{ // std::tie: function template, Constructs a tuple object whose elements are references ? // to the arguments in args, in the same order ? // std::ignore: object, This object ignores any value assigned to it. It is designed to be used as an ? // argument for tie to indicate that a specific element in a tuple should be ignored. ? ?? ? ? int myint; ? ? char mychar; ? ? ? std::tuple<int, float, char> mytuple; ? ? ? mytuple = std::make_tuple(10, 2.6, 'a'); ? ? ? ? ?// packing values into tuple ? ? ? std::tie(myint, std::ignore, mychar) = mytuple; ? // unpacking tuple into variables ? ? ? std::cout << "myint contains: " << myint << '\n'; ? ? std::cout << "mychar contains: " << mychar << '\n'; }
元組的元素類型獲取
獲取元組中某個元素的數(shù)據(jù)類型,需要用到另外一個類型: std::tuple_element。 語法: std::tuple_element<index, tuple>。
{ ? ? std::tuple<int, std::string> third(9, std::string("ABC")); ? ?? ? ? // 得到元組第1個元素的類型,用元組第一個元素的類型聲明一個變量 ? ? std::tuple_element<1, decltype(third)>::type val_1; ? ?? ? ? // 獲取元組的第一個元素的值 ? ? val_1 = std::get<1>(third); ? ? std::cout << "val_1 = " << val_1.c_str() << "\n"; }
元組的拼接
使用 std::tuple_cat 執(zhí)行拼接
{ ? ? std::tuple<char, int, double> first('A', 1, 2.2f); ? ? // 組合到一起, 使用auto, 自動推導(dǎo) ? ? auto second = std::tuple_cat(first, std::make_tuple('B', std::string("-=+"))); ? ? // 組合到一起,可以知道每一個元素的數(shù)據(jù)類型時什么 與 auto推導(dǎo)效果一樣 ? ? std::tuple<char, int, double, char, std::string> third = std::tuple_cat(first, std::make_tuple('B', std::string("-=+"))); ? ? // 輸出合并后的元組內(nèi)容 ? ? int index = 0; ? ? std::cout << index++ << " = " << std::get<0>(second) << "\n"; ?// 0 = A ? ? std::cout << index++ << " = " << std::get<1>(second) << "\n"; ?// 1 = 1? ? ? std::cout << index++ << " = " << std::get<2>(second) << "\n"; ?// ?2 = 2.2 ? ? std::cout << index++ << " = " << std::get<3>(second) << "\n"; ?// 3 = B ? ? std::cout << index++ << " = " << std::get<4>(second).c_str() << "\n"; // 4 = -=+ }
元組的遍歷
元組沒用提供operator []重載,遍歷起來較為麻煩,需要為其單獨提供遍歷模板函數(shù)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
C++?OpenGL實現(xiàn)旋轉(zhuǎn)立方體的繪制
這篇文章主要主要為大家詳細(xì)介紹了如何利用C++和OpenGL實現(xiàn)旋轉(zhuǎn)立方體的繪制,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起動手嘗試一下2022-07-07