C++中的tuple(元组)

tuple是类似于结构体,功能跟C语言中的结构体一样。在不需要创建结构体的前提下可以使用类似于结构体的功能

下面是touple的简单使用


//使用元组需定义的头文件

#include<tuple>

void main()

{

       //创建元组

std::tuple<int, char, double>tp(2, 'b', 1.9);
auto data0 = std::get<0>(tp);//获得里面的元素
auto data1 = std::get<1>(tp);
auto data2 = std::get<2>(tp);

auto tup1 = std::make_tuple("hello", 'a', 1.3);

        //上述代码创建了一个tuple <const char*, char, double>类型的元组。

const char * a;
char b;
double c;
std::tie(a, b, c) = tup1;
std::cout << a << "  " << b << "  " << c << std::endl;
std::tie(std::ignore, b, c) = tup1;
// tie: 用于拆开tuple
// 如果不想要某一位的值,可以直接将其用ignore代替。
int aa = 5;
int &bb = aa;
char *p = "hello";
char *&pp = p;


auto tup2 = std::forward_as_tuple(bb, pp);
auto data5 = std::get<0>(tup2);
std::cout <<"****"<< data5 << std::endl;
// forward_as_tuple: 用于接受右值引用数据生成tuple

//上述代码创建了一个tuple<int &&, char (*&)>类型的元组。

//意思就是可以使用右值作为参数,而前面讨论的tie函数就只能接受左值


std::tuple<float, std::string> tup1(3.14, "pi");
std::tuple<int, char> tup2(10, 'a');

auto tup3 = tuple_cat(tup1, tup2);

//将tup1和tup2连起来就成了tup3

std::cin.get()

}

还有很多其他的应用就不举例子了

猜你喜欢

转载自blog.csdn.net/qianyayun19921028/article/details/80923078