Home > Backend Development > C++ > body text

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

Barbara Streisand
Release: 2024-10-24 13:05:02
Original
859 people have browsed it

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>
Copy after login
<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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!