Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I not copy a C-style array to std::array? [duplicate]

Tags:

I have this code:

 std::array<int,16> copyarray(int input[16]) {     std::array<int, 16> result;     std::copy(std::begin(input), std::end(input), std::begin(result));     return result; } 

When I try to compile this code, I am getting this error:

'std::begin': no matching overloaded function found  

and a similar error for std::end.

What is the problem and how I can fix it?

like image 508
mans Avatar asked May 23 '18 13:05

mans


1 Answers

In parameter declaration, int input[16] is same as int* input. And when you pass argument array would decay to pointer, both mean the information about size of the array is lost. And std::begin and std::end can't work with pointers.

You could change it to pass-by-reference, which reserve the array's size.

std::array<int,16> copyarray(int (&input)[16]) 

Note that you can only pass array with exact size of 16 to the function now.

like image 98
songyuanyao Avatar answered Oct 26 '22 00:10

songyuanyao