为什么我不能将 C 样式数组复制到 std::array?
Why can I not copy a C-style array to std::array?
我有这个代码:
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::begin
和std::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;
}
相关文章:
- C++11 中不同类型的对象的 std::array 的替代方案
- constexpr begin of a std::array
- C++如果必须在编译时确定大小,std::array 有什么意义?
- 标准::unordered_map 中的 std::array 的值初始化
- 确保编译时的特定 std::array 位置
- std::array的长度有大小限制吗?
- 将 std::array 移动到另一个 std::array
- 检查输入 std::array 指针数据是否等于某个常量数组
- 如何读/写或遍历 std::array 中的特定元素范围?
- 是否可以使用 std::array 作为 POD 结构的数据容器?
- 如何在C++中传递一个大小未知的 std::array?
- 将 std::array 推回 std::vector N 次的优雅方式
- 如何在 c++11 中静态断言 std::array 类成员进行排序?
- unqualified sort() -- 为什么它在 std::vector 上使用而不是在 std::array 上
- 按值返回 std::array
- 如何将变量内容常量转换为 std::array 的大小?
- 将初始化器列表/聚合初始化转发到 std::array 成员
- 无法推断类中的类型,构造函数采用 std::array
- 为什么 char 可以在 std::array 中初始化为 nullptr,而不是单独初始化?
- C++ IDE 不会推断/自动完成对模板类中的 std::array 下标表达式的成员访问