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

+3


source to share


3 answers


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.

+4


source


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

0


source


Try using the following:

void Function(unsigned char*&dat1, unsigned char*&dat2, unsigned char*&dat3, ...)
{
      dat1 = new unsigned char[10];
      dat2 = new unsigned char[20];
      dat3 = new unsigned char[30];
      ....
}

      

This will pass the array pointer by reference.

0


source







All Articles