Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing inline double array as method argument

Consider method

functionA (double[] arg)

I want to pass a double array inline, like

functionA({1.9,2.8})

and not create an array first and then pass it, like

double var[] = {1.0,2.0};
functionA(var);

Is this possible with C++? Sounds simple, but I could not find a hint anyway concerning my question which made me suspicious :).

like image 933
Eric Avatar asked Jan 05 '12 08:01

Eric


2 Answers

You can do this with std::initializer_list<>

#include<vector>

void foo(const std::initializer_list<double>& d)
{ }

int main()
{
    foo({1.0, 2.0});
    return 0;
}

Which compiles and works for me under g++ with -std=c++0x specified.

like image 77
Yuushi Avatar answered Oct 15 '22 20:10

Yuushi


This works with c++0x

void functionA(double* arg){
   //functionA
}

int main(){
    functionA(new double[2]{1.0, 2.0});
    //other code
    return 0;
}

Although you need to make sure that the memory allocated by new is deleted in the functionA(), failing which you there will be a memory leak!

like image 29
Chethan Ravindranath Avatar answered Oct 15 '22 20:10

Chethan Ravindranath