天天看點

C++11 tuple

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進行“解包”操作。看下面的代碼:

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 <utility>

#include <string>

  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;

myauto contains:

3.14

pi

10

a

上一篇: C++11 thread
下一篇: nginx