How to transfer an array to a function without passing its size?
- I heard that you can still with the help of a template - nikita2002
2 answers
if it is the transfer of size that is interested in using the template function, then
template<std::size_t N> void f(int (&arr)[N]) { // N содержит количество элементов в переданном массиве } int main() { int arr[5]={0}; f(arr); return 0; } Edit: As such a concept, passing an array to a function does not exist. Instead, we can pass an array to a function in two ways.
- through the pointer
- via link to array
The template function f takes the case of passing an array through a link. Consider our example. Let's try to rewrite our function, removing the template in the definition. Considering that we are passing an array of 5 elements in size as a function parameter, the function f will look like this
void f(int (&arr)[5]) { } if an array with the size of 4 elements is transmitted, we must define the function as follows
void f(int (&arr)[4]) { } And so on.
That is, the declaration of functions is identical, except for the size of the transmitted array. Therefore, we template it and its parameter will take the size of the transmitted array.
When passing an array through a link, the function must determine the size of the array. Determining the size of an array is very simple.
int a[5]; n = sizeof(a)/sizeof(a[0]); Size determination is performed behind the scenes.
- can explain what is happening - nikita2002
- @ nikita2002, updated the answer. - Alexcei Shmakov
- How is the template parameter itself added? - nikita2002
- we do not write when we transmit
int<5> arr- nikita2002 - @ nikita2002, the template parameter is not added, we ourselves added it to the function definition. If the transfer of the array to the function does not work out, there will be a compilation error - Alexcei Shmakov
Send as a pointer, then the size will NOT be transferred exactly.
But if you want to transfer it so that the function knows how many elements there are, then you either need to transfer the size separately, or use not an array, but a class of type std::vector or std::array , or create a template function.