1.pair
pair<T1,T2> 模板定义在 utility 头文件中
初始化pair:
std::pair<std::string, std::string> his_pair{"test", std::string {"that"}};
auto your_pair = std::make_pair("test",std::string {"that"});//省略模板参数,自动推断,对象类型是 pair<const char*,string>
std::pair<std::string, std::string> new_pair;
new_pair.first = "his";
new_pair.second = "hers";
make_pair<T1,T2>
auto his_pair = std::make_pair<std::string, std::string>("test",std::string {"that"});
复制或移动构造
std::pair<std::string, std:: string> new_pair{my_pair};
old_pair = new_pair; // Copy assignment
pair 对象有全套的运算符 ==、!=、<、<=、>、>=, pair 对象的类型必须是相同的,先比较first在比较second
pair 的成员函数 swap()可以交换两个pair对象的成员值
p1.swap(p2)
2.tuple
tuple<> 模板可以封装不同类型的任意数量的对象,tuple 模板定义在 tuple 头文件中。当需要将多个对象当作一个对象传给函数时,tuple 类型是很有用的。
辅助函数 make_tuple()。这个函数可以接受不同类型的任意个数的参数
auto my_tuple = std::make_tuple (Name{"Peter”,"Piper"},42,std::string{"914 626 7890"}); //my_tuple 对象是 tuple<Name,int,string> 类型
构造:
(1)默认构造
std::tuple<std::string, size_t> my_tl
(2)值初始化
std:: tuple<Name, std::string> my_t2 {Name {"Andy", "Capp"},std::string{“Programmer”}};
(3)复制构造(用一个tuple初始化另一个tuple)
std::tuple<Name,std::string> copy_my_t2{my_t2}; // Copy constructor
(4)用 pair 对象构造 tuple 对象,pair 可以是左值,也可以是右值,此时tuple 只能有两个元素
auto the_pair = std::make_pair("these","those");
std::tuple<std::string, std::string> my_t4 {the_pair};//左值
std::tuple<std::string, std::string> my_t5 {std::pair <std::string, std::string > { "this", "that"}};//右值
可以用任何比较运算符来比较相同类型的 tuple 对象,tuple 对象的成员函数 swap() 交换两个tuple
tuple成员的访问:函数模板 get<>() 可以返回 tuple 中的一个元素
(1)模板参数为size_t
std::get<0>(my_tuple) //返回tuple中第一个元素的引用
(2)模板参数为成员类型,但要求 tuple 中只有一个这种类型的元素
std::get<Name>(my_tuple)
(3)全局的 tie<>() 函数模板(定义在 tuple 头文件中)