如何传递一个动态分配的数组,其中"运行时确定的大小"作为参考?

Shi*_*ora 1 c++ arrays reference

我知道如何传递一个常量大小的数组作为引用,但我想知道如何传递一个可变大小的数组作为对另一个函数的引用.任何帮助将非常感激.谢谢

例如,我有以下代码片段:

void y(int (&arr)[n]) //Gives error
{}

void x(Node * tree, int n)
{
     int arr[n];
     y(arr);
}
Run Code Online (Sandbox Code Playgroud)

我听说我们可以模板化函数并使大小成为模板参数,但我无法这样做.

Xir*_*ema 9

简单:不要.使用std::arraystd::vector代替:

int get_max(std::vector<int> & vec) {//Could use const& instead, if it doesn't need to be modified
    int max = std::numeric_limits<int>::min();
    for(int & val : vec) {if(max < val) max = val;
    return max;
}

int get_max(std::array<int, 20> & arr) {//Could use const& instead
    int max = std::numeric_limits<int>::min();
    for(int & val : arr) {if(max < val) max = val;
    return max;
}
Run Code Online (Sandbox Code Playgroud)

如果你想让它适用于任何std::array或任何std::vector,你可以像这样模板:

template<typename T>
T get_max(std::vector<T> const& vec) {
    if(vec.size() == 0) throw std::runtime_error("Vector is empty!");
    T const* max = &vec[0];
    for(T const& val : vec) if(*max < val) max = &val;
    return *max;
}

template<typename T, size_t N>
T get_max(std::array<T, N> const& arr) {
    static_assert(N > 0, "Array is empty!");
    T * max = &arr[0];
    for(T & val : arr) if(*max < val) max = &val;
    return *max;
}
Run Code Online (Sandbox Code Playgroud)

您的代码现在应该像这样来补偿:

void y(std::vector<int> & arr) //Can be const& if you don't need to modify it.
{}

void x(Node * tree, int n)
{
     std::vector<int> arr(n); //Will initialize n elements to all be 0.
     y(arr);
}
Run Code Online (Sandbox Code Playgroud)

  • @rubenvb对于那些需要了解代码*在逐步级别*上做什么的新程序员来说,这更有用.在更常规的情况下隐藏类型可能是完全合理的,但在回答OP所提出的问题时,它并不是有益的.此外,它们并没有完全相同*:后者因编译时错误而失败,如果用户确定他们不需要动态内存,这可能是有益的. (3认同)