C++11 tuple

weixin_33860553發表於2012-04-08

tuple元組定義了一個有固定數目元素的容器,其中的每個元素型別都可以不相同,這與其他容器有著本質的區別.是對pair的泛化。

首先來介紹元組的建立和元組元素的訪問。通過make_tuple()建立元組,通過get<>()來訪問元組的元素。通過下面這段程式來認識這兩個函式的用法:

#include <iostream>

#include <tuple>

#include <functional>

 

int main()

{

    auto t1 = std::make_tuple(10, "Test", 3.14);

    std::cout << "The value of t1 is "

              << "(" << std::get<0>(t1) << ", " << std::get<1>(t1)

              << ", " << std::get<2>(t1) << ")\n";

 

    int n = 1;

    auto t2 = std::make_tuple(std::ref(n), n);//ref表示引用

    n = 7;

    std::cout << "The value of t2 is "

              << "(" << std::get<0>(t2) << ", " << std::get<1>(t2) << ")\n";

}

執行結果為:

The value of t1 is (10, Test, 3.14)

The value of t2 is (7, 1)

 

接下來介紹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中的第二個元素.

 

最後介紹一個tuple_cat()函式,通過該函式可以將多個tuple連線起來形成一個tuple(注:在VC11中只能連線兩個tuple並不是真正的多個tuple)。

#include <iostream>

#include <utility>

#include <string>

#include <tuple>

 

int main ()

{

 

  std::tuple<float,std::string> mytuple (3.14,"pi");

  std::pair<int,char> mypair (10,'a');

 

  auto myauto = std::tuple_cat ( mytuple, mypair );

 

  std::cout << "myauto contains: " << std::endl;

  std::cout << std::get<0>(myauto) << std::endl;

  std::cout << std::get<1>(myauto) << std::endl;

  std::cout << std::get<2>(myauto) << std::endl;

  std::cout << std::get<3>(myauto) << std::endl;

 

  return 0;

}

執行結果:

 

myauto contains:

3.14

pi

10

a

相關文章