c++ 11 tie

tie()函式可以將變數連線到一個給定的tuple上,生成一個元素類型全是引用的tuple,相當於make_tuple(ref(a),ref(b),…)。可以通過tie()函式的使用方便的對tuple進行“解包”操作。

代碼,運行結果,

代碼

#include <iostream>
#include <tuple>
int main ()
{
int myint;
char mychar;
float myfloat;
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 【1】
std::tie (myint,myfloat, mychar) = mytuple;
std::cout << "myint contains: " << myint << std::endl;
std::cout << "mychar contains: " << mychar << std::endl;
std::cout << "myfloat contains: "<< myfloat <<std::endl;
std::get<0>(mytuple) = 100;//修改tuple的值
std::cout <<"After assignment myint contains: "<< std::get<0>(mytuple) << std::endl;
return 0;
}

運行結果

myint contains: 10
mychar contains: a
myfloat contains: 2.6
After assignment myint contains: 100
註:正如【1】處我們可以使用std::ignore,從而不用關聯tuple中的第二個元素.

相關詞條

熱門詞條

聯絡我們