Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use structured binding in an array passed as arg to some function?

Tags:

c++

c++17

I'm trying to decompose an array of 2 integers given to a function into x, y

It doesn't work when using int init[2] as a parameter. But it does when I change it to 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? And why it doesn't work when using int init[2]?

like image 783
Bruno Avatar asked May 11 '19 17:05

Bruno


People also ask

How do you bind an array to an anonymous variable?

In case of an array, structured binding also works pretty well. The number of identifiers in structured binding should be the same as the number of array elements: You can qualify the underlying anonymous variable with const or volatile. You can use “&” or “&&” to make it an lvalue or an rvalue reference.

How to pass an entire structure as an argument to function?

Now let’s see how to Pass an entire structure as an argument to function. Name of the structure variable is given as argument in function call. It is collected in another structure variable in function header. The disadvantage is that a copy of an entire structure is created again by wasting the memory.

What is structured binding in a structured binding declaration?

A structured binding declaration performs the binding in one of three possible ways, depending on E. Case 1 : if E is an array type, then the names are bound to the array elements. Case 2 : if E is a non-union class type and tuple_size is a complete type, then the “tuple-like” binding protocol is used.

What is structured binding in Python?

Structured binding allows you to initialize multiple variables with individual elements of a structure, tuple, or array. Often, a function will return multiple values packed in a structure.


1 Answers

int (&init)[2] is a reference to an array of two integers. int init[2] as a function parameter is a leftover from C++'s C heritage. 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.

A function taking int init[2] can be called with an array of any size, on account of actually taking a pointer. It may even be passed nullptr. While a function taking int(&)[2] may only be given a valid array of two as an argument.

Since in the working version init refers to a int[2] object, structured bindings can work with that array object. 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.

like image 113
StoryTeller - Unslander Monica Avatar answered Nov 12 '22 16:11

StoryTeller - Unslander Monica