是否可以使用 `std::copy` 将值从可变大小的数组复制到容器?

Is it possible to use `std::copy` to copy values from a variable-sized array to a container?

以下是 MergeSort 实现。我的 问题 是编译器抱怨 std::begin 不能应用于 可变大小的数组 temp 以便进一步使用 std:copy

我正在使用 C++17 和 gcc 8.3

template<typename Container, typename Iterator>
void Search::MergeSort(Container &array, Iterator begin, Iterator end)
{
    auto const len = end - begin;
    if (len > 1)
    {
        auto mid = begin + len / 2;
        MergeSort(array, begin, mid); 
        MergeSort(array, mid, end); 

        typename Container::value_type temp[len];

        int p = 0;
        for (auto i = begin, j = mid; i < mid; ++i)
        {
            auto curr = *i;
            while (j < end && *j < curr) temp[p++] = *j++;
            temp[p++] = curr;
        }

        auto temp_begin = std::begin(temp); // ! problem: unable to compile this line
        copy(temp_begin, temp_begin + p, begin);
    }

错误消息包括:

template argument deduction/substitution failed:
note: mismatched types 'std::initializer_list<_Tp>' and 'std::vector<int>::value_type*' {aka 'int*'}
      variable-sized array type 'std::vector<int>::value_type [len]' {aka 'int [len]'} is not a valid template argument

问题是 std::begin/end 没有为可变大小的数组定义。

可变大小数组是 C99 的一项功能,也是 C++ 的非标准扩展。然而,有时,它们是性能方面的最佳选择。

但是,可以使用普通指针算法获取可变大小数组的迭代器:

std::copy(temp + 0, temp + p, begin);

如果您的 C++ 编译器不支持某些平台(例如 Windows、Linux 和可能大多数类 Unix 平台)的此扩展,请提供 alloca 函数。请注意,这只是一个内存分配函数(类似于malloc),因此它不会调用构造函数或初始化分配的内存。

Is it possible to use std::copy to copy values from a variable-sized array to a container?

回答你的问题。 是的,就像的回答一样,可以做到。

但是,请不要使用变长数组s,因为依赖一些东西not part of C++ standard is a bad idea.

其次,C++提供了更好的选项,如std::vectors or std::arrays;因此只需使用它们。

例如,使用std::vector,您可以编写完全没有错误的合法代码(如评论中提到的@NathanOliver)。

#include <vector>

using value_type = typename Container::value_type;

/* or by iterator_traits
 * using value_type = typename std::iterator_traits<Iterator>::value_type;
 */
std::vector<value_type> temp(len);

如果 len 是编译时已知变量,您也可以使用 std::array