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

She*_*rry 3 c++ templates variable-length-array c++17 stdcopy

以下是一个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);
    }
Run Code Online (Sandbox Code Playgroud)

错误消息包括:

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
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

JeJ*_*eJo 7

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

回答您的问题。是的,就像@Maxim Egorushkin的回答一样,一个人可以做到。

但是,请不要使用可变长度数组 s,因为依赖C ++标准中不包含的内容是一个坏主意。

其次,C ++提供了更好的选项,例如std::vectors或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);
Run Code Online (Sandbox Code Playgroud)

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