C++ tuple元组的用法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34784043/article/details/82964423

 C++中的元组其实就是一个结构体模板类型,所以它的使用方法和结构体类似,下面程序是使用方法:

#include <iostream>
#include <tuple>//元组的头文件
#include <cstdlib>
#include <string>
using namespace std;

int main() {
	//创建元组
	tuple<string, int, string> person;
	//使用make_tuple给元组赋值
	person = make_tuple("陈大", 18, "男");
	//使用构造函数给元素赋值
	tuple<string, double, double> man(string("李明"), 177.1, 130);
	//可以使用auto变量直接赋值
	auto cat = make_tuple("猫猫", 7);
	//可以使用forward_as_tuple生成tuple
	auto dog = forward_as_tuple("旺旺", 8);

	//可以元组中套元组和类
	class House {
	private:
		double square;
	};
	House house;
	auto personHouse = make_pair(person, house);

	//使用tie函数拆开tuple,注意tie是放在左边
	string name;
	int age;
	string sex;
	tie(name, age, sex) = person;
	cout << name << " " << age << " " << sex << endl;

	//使用ignore可以拆开时忽略某一位
	tie(name, age, ignore) = person;
	cout << name << " " << age << endl;

	//使用get<i>()可以获取tuple中的元素
	cout << get<0>(person) << " " << endl;

	//使用tuple_size<>::value可以获得tuple中的元素个数
	cout << tuple_size<decltype(person)>::value << endl;

	//使用tuple_cat可以连接tuple
	auto personAndCat = tuple_cat(person, cat);
	cout << tuple_size<decltype(personAndCat)>::value << endl;

	system("pause");
	return 0;
}

运行结果: 

 

猜你喜欢

转载自blog.csdn.net/qq_34784043/article/details/82964423