为什么我不能将C风格的数组复制到std :: array?

man*_*ans 20 c++ arrays stl c++11 stdarray

我有这个代码:

 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;
}
Run Code Online (Sandbox Code Playgroud)

当我尝试编译此代码时,我收到此错误:

'std::begin': no matching overloaded function found 
Run Code Online (Sandbox Code Playgroud)

和类似的错误std::end.

有什么问题以及如何解决?

son*_*yao 40

在参数声明中,int input[16]int* input.相同.当你传递参数数组会衰减到指针时,两者都意味着有关数组大小的信息会丢失.而且std::beginstd::end不能使用指针工作.

您可以将其更改为传递引用,这将保留数组的大小.

std::array<int,16> copyarray(int (&input)[16])
Run Code Online (Sandbox Code Playgroud)

请注意,您现在只能将具有精确大小的数组传递16给函数.

  • ...或者使用原始指针(`input`和`input + 16`)来算法.当然不推荐,但有时别人别无选择 (11认同)
  • 你甚至可以添加缺少的`const`. (8认同)

Aco*_*gua 34

一切重要的已经,就可以得到功能更灵活的只是一点点:

template <typename T, size_t N>
std::array<T, N> copyarray(T const (&input)[N])
{
    std::array<T, N> result;
    std::copy(std::begin(input), std::end(input), std::begin(result));
    return result;
}
Run Code Online (Sandbox Code Playgroud)