C++特性

本文主要是C++语言中的一些tricks或不常见但有用的语法记录,边学边更新。

1、tie

基本概念

std::pair 即二元组,可以将不同的2个元素放在一起。

std::tuple 即三元组,可以理解为pair的扩展,可以用来将不同类型的三个元素存放在一起,常用于函数的多返回值。

std:pair<int, string> mypair;
mypair = std::make_pair(10, "hello");  // packing values into pair

std::tuple<int, float, char> mytuple;
mytuple = std::make_tuple(10, 2.6, 'a');  // packing values into tuple

std::tie 创建左值引用的 tuple,或将 元组 解包为独立对象,返回含左值引用的 对应元组 对象。

用处:

1、结构体比较

struct S {
    int n;
    std::string s;
    float d;
    bool operator<(const S& rhs) const {
        // 比较 n 与 rhs.n,
        // 然后为 s 与 rhs.s,
        // 然后为 d 与 rhs.d
        return std::tie(n, s, d) < std::tie(rhs.n, rhs.s, rhs.d);
    }
};

2、解构结构体,得到每个具体的元素值

int i;
double d;
string s;

tie(i, d, s) = t3;

cout << i << " " << d << " " << s << endl;

3、利用占位符std::ignore,得到部分元素的值

std::ignore介绍:任何值均可赋给而无效果的未指定类型的对象。目的是令 std::tie 在解包 std::tuple 时作为不使用的参数的占位符使用。

std::tie(myint, std::ignore, mychar) = mytuple;  // unpacking tuple into variables
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值