C++ tuple模板类使用体验

C++ tuple模板类使用体验

tuple类可以说是一种特殊的pair类型,其内部可以最大包含10个左右不同类型的成员(pair只能包含两个)
使用tuple需要包含头文件
对应std::make_pair,tuple也有对应的std::make_tuple模板函数用于创建特定类型的tuple对象
tuple主要有如下常用的操作

make_tuple

make_tuple用于创建一个指定类型的tuple对象,例如std::make_tuple<int, float, std::string>

get

get函数是一个模板函数,用法是get<N(0~10)>(tuple类型对象),模板参数是一个下标索引,标识想要获取tuple对象中的第几个成员。
另外,由于get是一个模板函数,因此无法使用for循环调用get来获取tuple类型对象中的每一个成员(因为需要编译期就确定模板参数,for的循环下标在编译期无法确定)

tie

tie用于将一些变量临时绑定称为一个tuple对象,即tuple<type1&, type2&,…> obj = tie(type1 obj1, type2 ,…);

下面这个例子说明了上面三个tuple操作的使用:

#include <iostream>
#include <tuple>
#include <string>

using namespace std;

int main(int argc, void* argv[])
{
    tuple<int, string> studentInfo = make_tuple(3, "lcb");
    cout<<"student number is:"<<get<0>(studentInfo)<<", name is:"<<get<1>(studentInfo)<<endl;
    cout<<"tuple size is:"<<tuple_size<decltype(studentInfo)>::value<<endl;
    int randomInt = 22;
    string randomStr = "fuXk";
    float randomFloat = 0.112;
    tuple<int, string, float> tieObject = tie(randomInt, randomStr, randomFloat);
    cout<<"tie object:"<<get<0>(tieObject)<<","<<get<1>(tieObject)<<","<<get<2>(tieObject)<<endl;
    getchar();
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值