结构化绑定声明(c++ 17)

绑定指定名称到初始化器的子对象或元素。

可以用于for循环,节省代码量,比如:

list<tuple<int, double, string>> list;
list.emplace_back(1, 9.9, "aa");
for (auto [i, d, s] : list)
{
    cout << i << " " << d << " " << s << endl;
}

详细用法

1. 绑定数组

int a[2] = {1,2};
 
auto [x,y] = a; // 创建 e[2],复制 a 到 e,然后 x 指代 e[0],y 指代 e[1]
auto& [xr, yr] = a; // xr 指代 a[0],yr 指代 a[1]

2. 绑定元组

float x{};
char  y{};
int   z{};
 
std::tuple<float&,char&&,int> tpl(x,std::move(y),z);
const auto& [a,b,c] = tpl;
// a 指名指代 x 的结构化绑定;decltype(a) 为 float&
// b 指名指代 y 的结构化绑定;decltype(b) 为 char&&
// c 指名指代 tpl 的第 3 元素的结构化绑定;decltype(c) 为 const int

3. 绑定成员对象

struct S {
    mutable int x1 : 2;
    volatile double y1;
};
S f();
 
const auto [x, y] = f(); // x 是标识 2 位位域的 int 左值
                         // y 是 const volatile double 左值

参考

结构化绑定声明 (C++17 起) https://api.wqcblog.run/C++/cpp-language-structured_binding.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值