Passing an std::array of Unknown Size to a Function
Problem:
How to create a function that operates on an std::array of known type but variable size?
Example:
<code class="cpp">// hypothetical example void mulArray(std::array<int, ?>& arr, const int multiplier) { for(auto& e : arr) { e *= multiplier; } }</code>
<code class="cpp">// imaginary arrays with values std::array<int, 17> arr1; std::array<int, 6> arr2; std::array<int, 95> arr3; mulArray(arr1, 3); mulArray(arr2, 5); mulArray(arr3, 2);</code>
Question:
Is there a straightforward approach to make this work, similar to C-style arrays?
Answer:
Unfortunately, no. Passing std::arrays of unknown size necessitates using function templates or alternative containers like std::vectors.
Template Solution:
<code class="cpp">template<std::size_t SIZE> void mulArray(std::array<int, SIZE>& arr, const int multiplier) { for(auto& e : arr) { e *= multiplier; } }</code>
Live Example: https://godbolt.org/z/T1d1n3vrM
The above is the detailed content of How to Handle std::arrays of Variable Size in Functions: A Straightforward Approach?. For more information, please follow other related articles on the PHP Chinese website!