HaskellPlease
HaskellPlease

Reputation: 277

Pass an array containing numbers as a parameter c++

I have a class with a constructor that takes three arguments

class Foo{
public: Foo(int, double[], double[]);
};

Foo::Foo(int a, double b[], double c[]){
// function
}

Now what I'm trying is to call this class with arrays that have fixed numbers for example

Foo(4, [4.1, 2.5, 7.2], [5.5, 6.1, 3.8]);

yet this doesn't work. Is such syntax possible in c++ or do I have to change it.

I tried doing it by declaring array variables before like

 double x[5];
 x[0] = 4.1;
 x[1] = 2.5;
 x[2] = 7.2;

 Foo(4, x, x);

this works but takes way to much time since I want to create multiple of these classes and this would make my code way bigger and unnecessary if there is a better way of doing it.

Thanks in Advance

Upvotes: 3

Views: 126

Answers (3)

Marek R
Marek R

Reputation: 38151

In such case std::initializer_list is best choice.

class Foo{
public:
    Foo(int n, std::initializer_list<double> a, std::initializer_list<double> b);
};

Foo foo { 32, {}, { 2, 3, 1, 2 }};

Live example.

Upvotes: 2

snowsignal
snowsignal

Reputation: 466

Declaring lists using [] will not work. But you can use brace enclosed initializer lists:

double b[] = {1.0, 2.0};
double c[] = {5.3, 4.7};
Foo f = Foo(1, b, c);

Note however, you cannot do this:

Foo f = Foo(1, {1.0, 2.0}, {5.3, 4.7});

Why? Because initializer lists can't convert inline to arrays. You have to declare the arrays explicitly. If you want to do this inline, use a std::vector<double>.

Upvotes: 1

kebs
kebs

Reputation: 6707

I would suggest using standard library containers:

class Foo{
   public:
     Foo(int, const std::vector<double>& vv ) : v(vv) 
     {
       // other stuff here
     }

     std::vector<double> v;
};

You can pass values this way, using aggregate initialization:

int main()
{
    Foo f( 1, {1.1,1.2,1.3} );
}

Or use std::array if compile-time fixed size.

Upvotes: 4

Related Questions