Home  >  Article  >  Backend Development  >  How to Handle std::arrays of Variable Size in Functions: A Straightforward Approach?

How to Handle std::arrays of Variable Size in Functions: A Straightforward Approach?

Barbara Streisand
Barbara StreisandOriginal
2024-10-24 13:05:02860browse

How to Handle std::arrays of Variable Size in Functions: A Straightforward Approach?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn