Returning multiple arrays from a function in C ++
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? Let's say like 2-10). I thought of one way to do this. One could simply pass the arrays to the void function by reference:
void function(int a[], int b[], double c[])
But then we can pass many arrays as input. I could package all my input arrays into a class, pass the class by reference, but that seems like an unnecessary structure. What is the correct way to do this? Thanks to
source to share
You can use std::vector
instead of arrays:
void function(vector<int> &a, vector<int> &b, vector<double> &c)
The caller of the function simply creates three vectors and passes them:
vector<int> a, b;
vector<double> c;
function(a, b, c);
and the function can edit vectors in any way (for example a.resize(10); a[0] = ...
), since the vectors used by this function are the same vectors passed by the caller. Thus, the function can "return" multiple vectors by modifying the vectors supplied by the caller.
source to share
you can use vector of vectors
std::vector<std::vector<double>> my2Dvec;
std::vector<double> vec1, vec2, vec3;
my2dvec.push_back(vec1);
my2dvec.push_back(vec2);
my2dvec.push_back(vec3);
my2dvec[0].push_back(123.123);
my2dvec[1].push_back(456.456);
my2dvec[2].push_back(789.789);
std::cout << my2dvec[0][0] << std::endl; // 123.123
std::cout << my2dvec[1][0] << std::endl; // 456.456
std::cout << my2dvec[2][0] << std::endl; // 789.789
//----------------------------------------
NOTE: vectors get slower the more changes you put into them. Therefore, if you have a vector of 3D vectors, remember about the velocity
source to share