Passing an inline double array as an argument to a method

Consider the method

functionA (double[] arg) 

I want to pass a double inline array like

 functionA({1.9,2.8}) 

instead of creating an array first and then passing it, e.g.

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

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

+6
source share
3 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 .

+8
source

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 the new one is deleted in the A () function, otherwise a memory leak will occur!

+5
source

You can do this in C ++ 11 using std::initializer_list .

 void fun(std::initializer_list<double>); // ... fun({ 1., 2. }); 

You cannot do this in C ++ 03 (or it will include a sufficient template, this will not be possible).

+3
source

Source: https://habr.com/ru/post/905173/


All Articles