[英]How to use structured binding in an array passed as arg to some function?
I'm trying to decompose an array of 2 integers given to a function into x, y
我正在尝试将给定函数的2个整数的数组分解为
x, y
It doesn't work when using int init[2]
as a parameter. 使用
int init[2]
作为参数时,它不起作用。 But it does when I change it to int (&init)[2]
. 但是当我将它改为
int (&init)[2]
时它int (&init)[2]
。
vector<vector<State>> Search(vector<vector<State>> board,
int init[2], int goal[2]) {
auto [x, y] = init;
}
What does (&init)
mean here? (&init)
在这里意味着什么? And why it doesn't work when using int init[2]
? 为什么在使用
int init[2]
时它不起作用?
int (&init)[2]
is a reference to an array of two integers. int (&init)[2]
是对两个整数数组的引用。 int init[2]
as a function parameter is a leftover from C++'s C heritage. int init[2]
作为函数参数是C ++ C语言遗留下来的剩余部分。 It doesn't declare the function as taking an array. 它没有将该函数声明为采用数组。 The type of the parameter is adjusted to
int*
and all size information for an array being passed into the function is lost. 参数的类型调整为
int*
,并且传递给函数的数组的所有大小信息都将丢失。
A function taking int init[2]
can be called with an array of any size, on account of actually taking a pointer. 由于实际采用指针,可以使用任意大小的数组调用
int init[2]
函数。 It may even be passed nullptr
. 它甚至可以通过
nullptr
。 While a function taking int(&)[2]
may only be given a valid array of two as an argument. 虽然采用
int(&)[2]
的函数只能给出一个有效的两个数组作为参数。
Since in the working version init
refers to a int[2]
object, structured bindings can work with that array object. 由于在工作版本中
init
引用了int[2]
对象,因此结构化绑定可以与该数组对象一起使用。 But a decayed pointer cannot be the subject of structured bindings, because the static type information available only gives access to a single element being pointed at. 但是,衰减的指针不能成为结构化绑定的主题,因为可用的静态类型信息只能访问指向的单个元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.