シンプル:しないでください。代わりに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);
}
配列を渡さないでください。 'std :: vector'を渡します。 –
@Shivam Arora C++は可変長配列をサポートしていません。 –
私はそうすることができると知っていますが、私は配列でそれを学びたいと思います。とにかく感謝します。 –