结构化绑定可以与std :: vector一起使用吗? [英] Does structured binding work with std::vector?

查看:131
本文介绍了结构化绑定可以与std :: vector一起使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以对向量使用结构化绑定?

Is it possible to use structured binding with vectors?

例如

std::vector<int> vec{1, 2, 3};
auto [a, b, c] = vec;

不幸的是,上述代码不起作用(在GCC下),但是也许有另一种方式(使用结构化绑定),它可以将向量的前三个值分配给三个变量。

Above code unfortunately doesn't work (under GCC), but maybe there's a different way (with structured binding) that allows to assign the first three values of a vector to three variables.

推荐答案

结构化绑定仅在结构为在编译时已知。 向量并非如此。

Structured binding only works if the structure is known at compile time. This is not the case for the vector.

虽然您知道各个元素的结构,但您确实知道不知道元素的数量,这就是您要在问题中分解的内容。同样,您只能对在编译时知道大小的数组类型使用结构化绑定。考虑:

While you do know the structure of the individual elements, you do not know the number of elements, and that is what you are trying to decompose on in your question. Similarly, you can only use structured bindings on array types where the size is known at compile time. Consider:

void f(std::array<int, 3> arr1,
       int (&arr2)[3],
       int (&arr3)[])
{
    auto [a1,b1,c1] = arr1;
    auto [a2,b2,c2] = arr2;
    auto [a3,b3,c3] = arr3;
}

前两个将起作用,但最后一行将无法编译,因为 arr3 的大小在编译时未知。 在Godbolt上试用

The first two will work, but the last line will fail to compile, because the size of arr3 is not known at compile time. Try it on godbolt.

这篇关于结构化绑定可以与std :: vector一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆