3

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

HaskellPlease
  • 277
  • 2
  • 10
  • 3
    Where did you learn that `[4.1, 2.5, 7,2]` is a C++ notation for an array? If you haven't and simply try to guess the C++ grammar, don't. Get [a good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) instead. – YSC Jan 16 '19 at 16:59
  • I am trying to get something that works as similar as this. Please read the entire question first. – HaskellPlease Jan 16 '19 at 17:04
  • A `double[]` parameter is actually a `double*` parameter. – molbdnilo Jan 16 '19 at 17:11
  • You are allowed to initialise arrays, you don't need to assign them elementwise – `double x[5] = {4.1, 2.5, 7.2};` – molbdnilo Jan 16 '19 at 17:13
  • Use `std::array` (or `std::vector`). – Jesper Juhl Jan 16 '19 at 17:31

3 Answers3

4

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.

kebs
  • 6,387
  • 4
  • 41
  • 70
2

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.

Marek R
  • 32,568
  • 6
  • 55
  • 140
1

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>.

  • *"Because initializer lists can't convert inline to arrays"* In `Foo(int a, double b[], double c[])`, `b` and `c` are actually pointers, not arrays. If you use const reference on array (as you can't pass array by value) the conversion happens: [Demo](http://coliru.stacked-crooked.com/a/cc7efd1017346aa4). – Jarod42 Jan 16 '19 at 19:00