Array Filling Function

How do you make a function that fills an array from its parameters and then puts those values back in the original array that was sent to the function?
*Not a vector, an array*
It's not clear what you mean by "fills an array from its parameters".
Do you mean a function you could call something like:
1
2
    int a[10];
    fillArray(a, {7, 4, 5, 9, 2, 3, 0, 8, 1, 6});

Last edited on
I meant call a function that would store values in an array. The array would be an array from the function, but then I want to put those values back in the original array that was sent to the function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <initializer_list>

template <typename T>
void fillArray(T *a, std::initializer_list<T> lst) {
    for (auto& x: lst) *a++ = x;
}

int main() {
    int a[10];
    fillArray(a, {7, 4, 5, 9, 2, 3, 0, 8, 1, 6});
    for (int x: a) std::cout << x << ' ';
    std::cout << '\n';
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
using namespace std;

//==========================================================

template <typename T> void fillArray( T *arr, T val )
{
   arr[0] = val;
}

//---------------------------

template <typename T, typename... Tail> void fillArray( T *arr, T val, Tail... values )
{
   arr[0] = val;
   fillArray( arr + 1, values... );
}

//==========================================================

int main()
{
   int a[5];
   fillArray( a, 10, 20, 30, 40, 50 );
   for ( int i : a ) cout << i << " ";
   cout << '\n';
}

//========================================================== 
consider memcpy(result, original, sizeinbytestomove); or std::copy

that would let you copy a result over an original very efficiently, assuming the array is not an array of pointers (it won't work in that case, or it may need additional scrutiny before doing it anyway)

It would solve this problem:

The array would be an array from the function, but then I want to put those values back in the original array that was sent to the function.

however the problem that we are solving may be a design flaw red flag.
generally, you don't want to cook up an array from an input array and then copy the answer over the original. this is woefully inefficient. If at all possible, you should directly modify the original and not have the temporary storage or copy operation at all. Some algorithms can avoid the temp and copy, and some can't so it just depends on what you are doing.

Last edited on
Topic archived. No new replies allowed.