测试环境visual stdio 2019,C++14
#include <iostream>
#include <string>
#include <set>
#include <tuple>
using namespace std;
//成对出现的数据,利用对组可以返回两个数据
void testPair()
{
//cteate pair,first method
pair<string, int>p("Tom", 20);
cout << "name: " << p.first << " age: " << p.second << endl;
//cteate pair,second method
pair<string, int>p2 = make_pair ("jerry", 30);
cout << "name: " << p2.first << " age: " << p2.second << endl;
}
/*
元组基本操作
关于元组的使用有三个核心的函数:
1. std::make_tuple: 构造元组
2. std::get: 获得元组某个位置的值
3. std::tie: 元组拆包
*/
template <typename T>
auto tuple_len(T& tpl) {
return std::tuple_size<T>::value;
}
void testTuple()
{
//name, age, height
tuple<string, int, int>t1= make_tuple("tom", 20, 180);
cout << "name: " << get<0>(t1) << " age: " << get<1>(t1) << " height: " << get<2>(t1) << endl;
//运行期索引问题
//std::get<> 依赖一个编译期的常量,所以下面的方式是不合法的:
//int index = 1;//index为变量,不合法 (C++ 17 引入std::variant<> 处理)
const int index = 1;//此时可编译通过
std::get<index>(t1);
cout << "std::get<index>(t1) age:" << std::get<index>(t1) << endl;
//元组合并
tuple<string, int, int>t2 = make_tuple("jerry", 30, 180);
cout <<"std::tuple_size<T>::value: " <<std::tuple_size<tuple<string, int, int>>::value << endl;
auto new_tuple = std::tuple_cat(t1, t2);
//auto new_tuple = std::tuple_cat(t1, std::move(t2));
auto res = tuple_len(new_tuple);
cout << "tuple_len(new_tuple)" << res << endl;
// 元组进行拆包
string name;
int age;
int height;
std::tie(name, age, height) = t1;
cout << name << "," << age << "," << height << endl;
//std::get 除了使用常量获取元组对象外,C++14 增加了使用类型来获取元组中的对象:
std::tuple<std::string, double, double, int> t("123", 4.5, 6.7, 8);
std::cout << std::get<std::string>(t) << std::endl;
//std::cout << std::get<double>(t) << std::endl; // 非法, 引发编译期错误
std::cout << std::get<3>(t) << std::endl;
}
int main()
{
testPair();
testTuple();
return 0;
}