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)
我听说我们可以模板化函数并使大小成为模板参数,但我无法这样做.
简单:不要.使用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;
}
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)