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

#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

你可能感兴趣的:(C++)