c++ tuple元組

tuple<> 模板是 pair 模板的泛化,但允許定義 tuple 模板的實例,可以封裝不同類型的任意數量的對象,因此 tuple
實例可以有任意數量的模板類型參數。tuple 模板定義在 tuple 頭文件中。

意思就是類似pair模板一樣,pair模板只能有兩個參數,但是tuple模板可以有好多個。
以下所有用到的函數都是tuple頭文件裏的

  1. 初始化
tuple<string,int,char> my_tuple[10];
my_tuple[0] = std::make_tuple ("Piper",42,'a');
  1. 獲取值
cout << get<int>(my_tuple[0]); //用類型獲取,但是類型不能定義的有同樣的,不然會編譯錯誤
cout << get<1>(my_tuple[0]);  //用下標獲取,從0開始,類型可以定義同樣的
int a=1,b=2,c=3;
auto tp = tie(a, "aa", b);   //tp的類型實際是:std::tuple<int&,string&, int&>
cout << get<0>(tp);
int x=5,y=5;
tie(x,ignore,y)=tp;
cout << x << y;

通過tie解包後,tp中三個值會自動賦值給三個變量。
解包時,我們如果只想解某個位置的值時,可以用std::ignore佔位符來表示不解某個位置的值。比如我們只想解第三個值時:
std::tie(std::ignore,std::ignore,y) = tp; //只解第三個值了

  1. tuple_cat() 函數
std::tuple<int, string, float> t1(10, "Test", 3.14);
int n = 7;
auto t2 = tuple_cat(t1, make_pair("Foo","bar"), t1, tie(n));
n = 10;
cout << get<8>(t2) << endl;

輸出10是因爲tie是引用的

  1. 獲取長度
int size = tuple_size<decltype(t2)>::value;
cout << size << endl;

decltype是獲得()參數裏面的變量的類型
在這裏插入圖片描述
6. tuple_element

auto my = std::make_tuple (10,'a');

std::tuple_element<0,decltype(my)>::type first = std::get<0>(my); // 前面可以直接用auto替代
std::tuple_element<1,decltype(my)>::type second = std::get<1>(my);

std::cout << "mytuple contains: " << first << " and " << second << '\n';
  1. forward_as_tuple: 用於接受右值引用數據生成tuple
string str ("John");
auto out = [](tuple<string,int> t){cout << get<0>(t) << get<1>(t) << endl;};
out(forward_as_tuple(str+" Daniels",22));
out(forward_as_tuple(str+" Smith",25));
  1. tuple比較
    tuple 對象中的元素是按照字典順序比較的
    只有所有元素全部相等兩個tuple才相等
auto t3=t1;
cout << (t1<t3) << endl;
cout << (t1==t3) << endl;
  1. tuple交換
tuple<int, std::string, float> t4(11, "Test", 3.14);
cout << get<0>(t3) << " " << get<0>(t4) << endl;
t3.swap(t4);	
cout << get<0>(t3) << " " << get<0>(t4) << endl;
  1. 排序
bool cmp(tuple<string,int,char> a,tuple<string,int,char> b){
	return a<b;
	return get<1>(a)<get<1>(b);	// 也可以按某列排序
}
main(){
	tuple<string,int,char> my_tuple[10];
	my_tuple[0] = std::make_tuple ("Pipr",42,'a');
	my_tuple[1] = std::make_tuple ("Piper",41,'a');
	my_tuple[2] = std::make_tuple ("Pper",45,'a');
	my_tuple[3] = std::make_tuple ("Pier",49,'a');
	for(int i=0;i<4;++i){
		cout << get<0>(my_tuple[i]) << " " << get<1>(my_tuple[i]) << " ";
	}
	cout << endl;
	sort(my_tuple,my_tuple+4,cmp);
	for(int i=0;i<4;++i){
		cout << get<0>(my_tuple[i]) << " " << get<1>(my_tuple[i]) << " ";
	}
	cout << endl;
}

官方文檔:http://www.cplusplus.com/reference/tuple/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章