pair/tuple

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 头文件中)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值