Make a method that return an array

Hello!

How can I do a method that returns an array?

I’ve found in some web pages that it can be done using

 Double_t method()[2]{

 }

But I’ve tried this, and ROOT doesn’t recognize the syntaxis.

Is there another simple way to do this or something like that? I want to obtain more than one variable from the same method.

Thanks very much!

Bye!

Hi,
use

Cheers, Axel.

But

void meth(std::vector<Double_t>& out)

doesn’t mean that the method return a vector. The vector is an argument.

I think it means that you can set the values of vector out with the method meth. But I’m interested in the Getmeth mehod, to get the values of the vector.

So to get a vector I’am looking for a method that returns a vector. Or in this cased a method that returns an array.

Bye!

Hi,
why do you think you needa method returning an array? I don’t want to appear arrogant here, but if you wonder about questions like these you really should use a vector&, fill it in the method, and use it from outside: [code]void MyFunc(std::vector<Double_t>& out) {
out.clear(); // reset whatever was in out
out.resize(10, 0.); // make sure out has exactly 10 elements
for(Int_t = 0; i < 10; ++i)
out[i] = i*0.1; // and set their values
}

Double_t AverageOfMyFunc() {
// cald the average of MyFunc’s vector
std::vector<Double_t> values;
MyFunc(values); // set values
Double_t ret = 0.;
for (Int_t i = 0; i < values.size(); ++i)
ret += values[i];
return ret / values.size();
}[/code]It’s efficient and safe. If you really need to return an array (again - I doubt you need that) then use the Double* MyFunc() syntax I already mentioned in my previous posting.

Axel.

Thanks!

I could use a dinamic array or a vector, but I think is more easier with arrays than with vectors. I only need an array with a dimension that can be fixed with a variable, instead of use a value, as with simple arrays in C. I don’t need to add elements to the array without the dimension fixed, like a vector, and also, is more complicated than arrays I think, is more advanced.

Bye!

I’ll try this.

We cannot return arrays, neither in C, not in C++ (but we can return reference to array or pointer to array).

  1. If you do not want to use a vector and you know the exact size, you can pass a reference to array.

void fun(double (&rarr)[2])
{
////
}

int main()
{
double arr[2] = {};
fun(arr);
}

But if you know an exact size, why don’t you use simple pointer?
2.

void fun(double * arr)
{
//
}

int main()
{
double arr[2] = {};
fun(arr);
}

If you want to return array, you can use simple workaround:

struct Agg{
double arr[2];
};

Agg fun()
{
//Here you can even use an initializer:
Agg a = {1., 2.};

return a;
}