我知道如何传递一个常量大小的数组作为引用,但我想知道如何将一个可变大小的数组作为对另一个函数的引用。任何帮助将非常感激。谢谢
例如,我有以下代码段:
void y(int (&arr)[n]) //Gives error
{}
void x(Node * tree, int n)
{
int arr[n];
y(arr);
}
我听说我们可以将函数模板化并将大小设为模板参数,但我无法这样做。
答案 0 :(得分:9)
简单:不要。请改用std::array
或std::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);
}
答案 1 :(得分:0)
Xirema已经提到了如何使用std::vector
/ std::array
解决此问题。
我不知道您的具体情况,所以只会描述其他选项,尽管std::vector
/ std::array
是最好的。
您相信,arr
的{{1}}和n
参数是一致的。并手动处理y
尺寸。
arr
这将起作用,它将在每个新的void y(int * arr, const int n) {}
void x(Node * tree, int n) {
int arr[n];
y(arr, n);
}
值上实例化2个模板。
N
答案 2 :(得分:0)
这个答案是为了说明如何在将CLA作为函数参数传递时在C ++中使用VLA。
在c99中,语法允许您将数组的大小作为参数传递给函数,并使用函数参数来声明VLA的大小:
state.settings
C ++使用&#34;函数名称修改&#34;作为将函数接受的参数类型编码到函数名中以支持函数重载的技术。但是,在GCC中,由于VLA不是C ++支持的功能,因此没有任何修改约定。有人可能会说这是一个G ++错误(或者对VLA扩展的不完全支持),但它就是它。要通过引用模仿传递,请接受衰减指针作为参数,并将其转换为对VLA的引用。
void y (int n, int (*arr)[n])
{}
void x (int n)
{
int arr[n];
y(n, &arr);
}
我已经确认这适用于GCC 4.8。