为什么我不能将 C 样式数组复制到 std::array?

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

本文关键字:std array 复制 数组 不能 样式 为什么      更新时间:2023-10-16

我有这个代码:

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;
}

当我尝试编译此代码时,出现此错误:

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

以及std::end的类似错误。

问题是什么,我该如何解决?

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

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

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

请注意,您现在只能将确切大小为16的数组传递给函数。

所有重要的事情都已经说了,你可以让函数更灵活一点:

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;
}

(后期(编辑:上述方法有一个缺点:您需要在分配时复制返回的数组,因为它不包含任何真正可移动的数据(对于原始数组来说已经是一样的(。您可以通过直接复制到目标数组来避免此缺点:

template <typename T, size_t N>
void copyarray(std::array<T, N>& target, T const (&source)[N])
{
std::copy(std::begin(source), std::end(source), std::begin(target));
}

这模仿了赋值target = source;如果你喜欢更好的,你可以交换参数,当然,让输出参数最后。

用法(按原样(:

int source[7] = { };
std::array<int, sizeof(source)/sizeof(*source)> target;
copyarray(target, source);

如前所述,这里的问题是数组在传递给函数时衰减到指针,这意味着大小不会保留。

但是,如果您知道数组中有 16 个元素,则可以这样做:

array<int,16> copyarray(const int input[]) {
array<int, 16> result;
copy_n(input, size(result), begin(result));
return result;
}