代码之家  ›  专栏  ›  技术社区  ›  mans

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

  •  20
  • mans  · 技术社区  · 7 年前

    我有这个代码:

     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 .

    3 回复  |  直到 7 年前
        1
  •  40
  •   songyuanyao    7 年前

    在参数声明中, int input[16] 与…相同 int* input . 当你传递参数数组 decay to pointer ,都意味着有关数组大小的信息将丢失。以及 std::begin std::end

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

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

    16 现在就到功能区。

        2
  •  34
  •   Aconcagua    6 年前

    所有重要的事 said 现在,您可以让函数更加灵活:

    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);
    
        3
  •  1
  •   Jonathan Mee    7 年前

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

    如果你 知道

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