I have a function where I would like to return multiple arrays. I know that in c++ does not return an array, but instead returns a pointer to an array. For example:
int* function(double array[])
But what if I need to return multiple arrays (multiple pointers to arrays? say like 2-10). I have thought of one way of doing this. One would be to just pass the arrays to a void function by reference:
void function(int a[], int b[], double c[])
But then we might be passing a lot of arrays as input. I could package all my input arrays into a class, pass the class by reference, but this seems like unnecessary structure. What is the right way to do this? Thanks
You can use std::vectors instead of arrays:
void function(vector<int> &a, vector<int> &b, vector<double> &c)
The function caller simply makes three vectors and passes them in:
vector<int> a, b;
vector<double> c;
function(a, b, c);
and the function can edit the vectors any way it likes (e.g. a.resize(10); a[0] = ...), since the vectors that the function uses are the same vectors that the caller passed in. In this way, the function can "return" multiple vectors by changing the vectors passed in by the caller.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With