C++ 为什么我不能将C样式的数组复制到std::array?
我有以下代码:C++ 为什么我不能将C样式的数组复制到std::array?,c++,arrays,c++11,stl,stdarray,C++,Arrays,C++11,Stl,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; } 对于std::end,也有类似的错误 问题是什么以及如何解决?在参数声明中,int-input[16]与int*in
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::end
,也有类似的错误
问题是什么以及如何解决?在参数声明中,
int-input[16]
与int*input
相同。当您传递参数数组时,两者都意味着关于数组大小的信息丢失。而且不能使用指针
您可以将其更改为通过引用传递,从而保留数组的大小
std::array<int,16> copyarray(int (&input)[16])
std::数组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;
}
如前所述,这里的问题是数组在传递给函数时会衰减为指针,这意味着不会保留大小 但是,如果您知道阵列中有16个元素,则可以执行以下操作:
array<int,16> copyarray(const int input[]) {
array<int, 16> result;
copy_n(input, size(result), begin(result));
return result;
}
数组copyarray(常量int输入[]){
数组结果;
复制(输入、大小(结果)、开始(结果));
返回结果;
}
数组参数的大小不是这样工作的,它等于int*input
@Slava如何修复它?只是不要使用C样式的数组。它们不知道大小,当用作函数参数时会转换为指针。没有std::begin
重载接受指针类型。@问题的目的可能是避免数组-可能代码管理器中的某个地方存在无法更改的数组?您也可以使用std::memcpy(result.data(),input,sizeof(input)),在它们之间进行复制
将两个数组大小定义为相同的constexpr size\u t
值可能是一个好习惯。如果在多个位置重新键入16
,并且它们不同步,则会出现缓冲区溢出或下溢…或者使用原始指针(input
和input+16
)进行算法。当然不推荐,但有时没有其他选择。您甚至可以添加缺少的const
。如果未连接到16,您可以使用模板数组copyarray(const int(&input)[N]){…}
保留大小。编辑——Aconcagua以这种方式进行参数化,但同时使用class T
而不是int
。@JohnP是的,只是将其作为一种替代方法来表示。模板是从到std::array
definition@UlrichVonRekkenin你想说什么?模板参数是相同的,因为它们必须是相同的,否则如何才能对数组进行常规引用?这种模式还出现在许多其他位置——例如,您是否查看过阵列的std::begin/end变体?
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));
}
int source[7] = { };
std::array<int, sizeof(source)/sizeof(*source)> target;
copyarray(target, source);
array<int,16> copyarray(const int input[]) {
array<int, 16> result;
copy_n(input, size(result), begin(result));
return result;
}