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

  • A+

This question already has an answer here:

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?

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.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: