且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

结构化绑定可以与std :: vector一起使用吗?

更新时间:2022-05-27 05:10:54

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

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.