gpt4 book ai didi

c++ - 如何传递以 "size determined at run time"作为引用的动态分配数组?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:25:00 25 4
gpt4 key购买 nike

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

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

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

void x(Node * tree, int n)
{
int arr[n];
y(arr);
}

我听说我们可以将函数模板化并将大小作为模板参数,但我做不到。

最佳答案

很简单:不要。使用 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;
}

如果您希望它适用于任何 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;
}

您的代码现在应该如下所示以补偿:

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);
}

关于c++ - 如何传递以 "size determined at run time"作为引用的动态分配数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44833759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com