with open as f用法_UE4精品教程 | C++Tuple元组的详细用法

哈喽,大家好,我叫人宅,很高兴和大家一起分享一下元组教学。

元组的这个词在很多语言里面已经有涉及到,使用上非常简洁,tuple是泛化的std::pair,我们通常是把它当作一个结构体使用,比如我们可以将多个参数整合为一个结构体传递到函数内部,实现一些简洁的操作。

1.tuple创建与基础使用方式

tuple tu = make_tuple(1,2.f,3,4.f);//创建方式一
tuple tu(1,2.f,3,4.f);//创建方式二
//相当于结构体:
struct tu
{
  int a;
  float b;
  int c;
  float d;
}

以上的创建方式只是实参的拷贝,如果我们修改这些参数是无法真正修改实际的参数的值

当然我们还可以有直接修改参数的方式

int a = 0;
float b = .f;
int c = 0;
float d = .1;

auto tu = tie(a,b,c,d);

//本地进行修改
get<0> (tu) = 2;
get<1> (tu) = 4.5f;
get<2> (tu) = 234;
get<2> (tu) = 22.f;

//当然还可以这么用
auto tu1 = make_tuple(1,2.f,3,4.f);

除此之外我们还可以使用forward_as_tuple构造我们的元组 这种构造是可以直接使用参数的原始引用 。

注意:如果是值,无法赋值,因为地址不一样;

int a = 0;
float b = .f;
int c = 0;
float d = .1;

auto tu = forward_as_tuple(a,b,c,d);

get<0> (tu) = 2;
get<1> (tu) = 4.5f;
get<2> (tu) = 234;
get<2> (tu) = 22.f;

cout << a<< endl;
cout << b<< endl;
cout << c<< endl;
cout << d<< endl;

错误使用

auto tu = forward_as_tuple(1,2.f,3,4.f);

get<0> (tu) = 2;
get<1> (tu) = 4.5f;
get<2> (tu) = 234;
get<2> (tu) = 22.f;

//地址不一样

2.获取tuple的数量

tuple a(2, 3, 1, 4);
size_t Num= tuple_size::value;
cout << "Num = " << Num<< endl;

3.获取tuple类型

tuple a(2, 3, 1, 4);
tuple_element<1, decltype(a)>::type t = std::get<0>(a);
cout << "t = " << t << endl;

4.拼接元组

tuple a(2, 3, 1, 4);
tuple b(2, 3, 1, 4);
tuple c(2, 3, 1, 4);
//拼接
auto TT = tuple_cat(a, b, c);

5.元组的简易实现原理

#include 
using namespace std;
template
class Tuple;
template<>
class Tuple<>
{
};
template
class Tuple :private Tuple
{
using InheritedTuple = Tuple;
public:
Tuple()
{}
Tuple(TupleHead v, TupleTail... vtail)
:MyHead(v), InheritedTuple(vtail...)
{}
TupleHead Head() { return MyHead; }
InheritedTuple& Tail() { return *this; }
protected:
TupleHead MyHead;
};
int main()
{
Tuple c (1, 5.f, 3);
system("pause");
return 0;
}

6.打印tuple全部的值

遍历tuple是非常麻烦的事情,以下提供了很好的遍历打印

#include 
#include
#include
#include
using namespace std;
template
struct PrintTuple
{
static void Printf(const Tuple& Value)
{
PrintTuple::Printf(Value);
cout << "," << get(Value);
}
};
template
struct PrintTuple
{
static void Printf(const Tuple& Value)
{
    cout << get<0>(Value);
}
};
template
void PrintfMyTuple(const tuple& vlaue)
{
     PrintTuple::Printf(vlaue);
}
int main()
{
tuple a(2, 3, 1, 4);
PrintfMyTuple(a);
system("pause");
return 0;
}

以上是std C++ tuple用法,除此之外元组还可以比较。

转载于人宅知乎文章

1ba1c38c81ad5de73189d365e37d564b.png

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值